模型Mixin中的Django GenericRelation

时间:2015-01-23 17:17:23

标签: django generic-relations

我有mixin和model:

class Mixin(object):
    field = GenericRelation('ModelWithGR')

class MyModel(Mixin, models.Model):
   ...

但是django不会将GenericRelation字段转换为GenericRelatedObjectManager

>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelation>

当我将字段放入模型本身或抽象模型时 - 它工作正常:

class MyModel(Mixin, models.Model):
   field = GenericRelation('ModelWithGR')

>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelatedObjectManager at 0x3bf47d0>

如何在mixin中使用GenericRelation

1 个答案:

答案 0 :(得分:6)

您始终可以继承Model并将其设为摘要,而不是从object继承。 Python的mro会解决所有问题。 像这样:

class Mixin(models.Model):
    field = GenericRelation('ModelWithGR')

    class Meta:
        abstract = True

class MyModel(Mixin, models.Model):
    ...