7

我有混合和模型:

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>

如何GenericRelation在 mixin 中使用?

4

1 回答 1

6

您始终可以从 继承Model并使其抽象,而不是从object. Python 的 mro 将解决所有问题。像这样:

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

    class Meta:
        abstract = True

class MyModel(Mixin, models.Model):
    ...
于 2015-01-27T03:54:31.700 回答