簡體   English   中英

Django - 模型混合不能按預期工作

[英]Django - model mixin doesn't work as expected

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嗎?

你的 mixin 必須是抽象的,並且我認為繼承應該來自 models.Model。

class PipedriveSyncRelatedMixin(models.Model):
    pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')

    class Meta:
        abstract = True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM