代码之家  ›  专栏  ›  技术社区  ›  dabadaba

仅为行为子类化Django模型

  •  1
  • dabadaba  · 技术社区  · 7 年前

    我有一个模型 Property 对于某些字段和相关方法:

    class Property(models.Model):
        table = models.ForeignKey(Table)
        field1 = models.CharField()
        field2 = models.IntegerField()
        field3 = models.BooleanField()
    
        class Meta:
            abstract = True
    
        def post():
            pass
    

    但从概念上讲,我有一定数量的列类型。这些字段没有区别,只有在如何实现某个方法的行为方面:

    class Property1(Property):
        def post():
            # execute behavior for Property1
            pass
    
    class Property2(Property):
        def post():
            # execute behavior for Property2
            pass
    

    等等。

    如果我转身 财产

    但同时运行查询以获取表中的所有属性并调用 post() 我希望执行相应的行为:

    for prop in table.property_set.all():
        prop.post()
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   ruddra    7 年前

    为此,你可以使用 proxy 模型。像这样试试:

    class Property(models.Model):
        table = models.ForeignKey(Table)
        field1 = models.CharField()
        field2 = models.IntegerField()
        field3 = models.BooleanField()
    
    
    class Property1(Property):
        class Meta:
           proxy = True
    
        def post():
            # execute behavior for Property1
            pass
    
    class Property2(Property):
    
        class Meta:
           proxy = True
    
        def post():
            # execute behavior for Property2
            pass
    

    MyPerson类与其父Person类在同一数据库表上操作。特别是,任何人的新实例也可以通过MyPerson访问,反之亦然:

    Property1.objects.filter(pk__in=table.property_set.all())