【问题标题】:Django - model mixin doesn't work as expectedDjango - 模型混合没有按预期工作
【发布时间】: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


【解决方案1】:

你的 mixin 必须是抽象的,继承应该来自 models.Model 我认为。

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

    class Meta:
        abstract = True

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 2021-01-31
    • 2021-09-23
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    相关资源
    最近更新 更多