【发布时间】:2019-03-19 13:55:57
【问题描述】:
在PipedriveSync 模型中,我使用GenericForeignKey,因此任何模型都可以与PipedriveSync 对象相关。
class PipedriveSync(TimeStampedModel):
...
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
我使用GenericRelation 能够向后引用这个对象。例如user.pipedrivesyncs.all()
看看User
class User(AbstractUser):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
由于我必须为许多模型指定相同的 pipedrivesyncs,因此我决定为此创建一个 mixin(那里也有几个方法,但现在没关系了)。
class PipedriveSyncRelatedMixin():
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
我就是这样用的
class User(PipedriveSyncRelatedMixin,AbstractUser):
pass
问题在于,当我手动指定 pipedrivesyncs 时,这个 Mixin 无法正常工作。
手动指定pipedrivesyncs的情况:
> u = User.objects.first()
> u.pipedrivesyncs.first()
> <PipedriveSync: PipedriveSync object (20)>
使用Mixin时的案例
> u = User.objects.first()
> u.pipedrivesyncs.first()
> AttributeError: 'GenericRelation' object has no attribute 'first'
区别在哪里,我可以为此使用Mixin吗?
【问题讨论】:
-
你跑
makemigrations了吗? -
有趣。您是否将 PipedriveSyncRelatedMixin 设为抽象模型?
-
@DanielRoseman 它使用 Mixin 作为抽象模型。 qaru.site/questions/821978/…谢谢
标签: python django django-models mixins django-2.1