zym*_*mud 7 django generic-relations
我有mixin和型号:
class Mixin(object):
field = GenericRelation('ModelWithGR')
class MyModel(Mixin, models.Model):
...
Run Code Online (Sandbox Code Playgroud)
但是django不会把GenericRelation场变成GenericRelatedObjectManager:
>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelation>
Run Code Online (Sandbox Code Playgroud)
当我将字段放入模型本身或抽象模型时 - 它工作正常:
class MyModel(Mixin, models.Model):
field = GenericRelation('ModelWithGR')
>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelatedObjectManager at 0x3bf47d0>
Run Code Online (Sandbox Code Playgroud)
我怎样才能GenericRelation在mixin中使用?
您始终可以从中继承Model并使其成为抽象而不是从中继承object.Python的mro会解决所有问题.像这样:
class Mixin(models.Model):
field = GenericRelation('ModelWithGR')
class Meta:
abstract = True
class MyModel(Mixin, models.Model):
...
Run Code Online (Sandbox Code Playgroud)