仅为行为子类化Django模型
我有一个带有特定字段和相关方法的模型仅为行为子类化Django模型,django,django-1.8,Django,Django 1.8,我有一个带有特定字段和相关方法的模型属性: class Property(models.Model): table = models.ForeignKey(Table) field1 = models.CharField() field2 = models.IntegerField() field3 = models.BooleanField() class Meta: abstract = True def post():
属性
:
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
等等
如果我将Property
转换为一个抽象的基本模型类,并让其余的继承它,那么我将为每个属性创建不同的表。我不确定我想要那个。所有表看起来都一样,这是多余的
但在运行查询以获取表中的所有属性并调用post()
的同时,我希望执行相应的行为:
for prop in table.property_set.all():
prop.post()
我的选择是什么?为此,您可以使用模型。试着这样做:
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
Property1.objects.filter(pk__in=table.property_set.all())
根据文件:
MyPerson类在与其父Person类相同的数据库表上操作。特别是,任何新的Person实例也可以通过MyPerson访问,反之亦然:
因此,您可以获得如下代理实例:
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
Property1.objects.filter(pk__in=table.property_set.all())
这缺少了我提到的最后一个要求,即返回每个子类的适当实例,而不是返回基类。@dabadaba请查看我更新的答案。希望能帮上忙。那没什么用。所做的只是强制将所有表属性强制转换到给定的子类中,不管它是否是该子类的一个实例。也许您可以研究以下答案: