在 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()
看看用户
class User(AbstractUser):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
由于我必须为许多模型指定相同的 pipedrivesyncs
,因此我决定为此创建一个 mixin(那里也有几种方法,但现在并不重要)。
class PipedriveSyncRelatedMixin():
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
我就是这样使用的
class User(PipedriveSyncRelatedMixin,AbstractUser):
pass
问题是,当我手动指定 pipelinedrivesyncs 时,这个 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 必须是抽象的,继承应该来自模型。我认为模型。
class PipedriveSyncRelatedMixin(models.Model):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
class Meta:
abstract = True
关于python - Django - 模型 mixin 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242708/