[英]Django - model mixin doesn't work as expected
In PipedriveSync
model I use GenericForeignKey
so any model can have PipedriveSync
object related.在
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')
And I use GenericRelation
to be able to reference backwards this object.我使用
GenericRelation
能够向后引用这个对象。 For example user.pipedrivesyncs.all()
例如
user.pipedrivesyncs.all()
Take a look at User
看看
User
class User(AbstractUser):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
Since I have to specify the same pipedrivesyncs
for many models, I decided to create a mixin for that (there are couple of methods there too but it doesn't matter now).由于我必须为许多模型指定相同的
pipedrivesyncs
,我决定为此创建一个 mixin(那里也有几种方法,但现在无关紧要)。
class PipedriveSyncRelatedMixin():
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
And I use it this way我是这样用的
class User(PipedriveSyncRelatedMixin,AbstractUser):
pass
The problem is that this Mixin
doesn't work the way it works when I specify pipedrivesyncs manually.问题是当我手动指定 pipedrivesyncs 时,这个
Mixin
无法正常工作。
Case of specifying pipedrivesyncs
manually:手动指定
pipedrivesyncs
:
> u = User.objects.first()
> u.pipedrivesyncs.first()
> <PipedriveSync: PipedriveSync object (20)>
Case when using Mixin
使用
Mixin
案例
> u = User.objects.first()
> u.pipedrivesyncs.first()
> AttributeError: 'GenericRelation' object has no attribute 'first'
Where is the difference and can I use Mixin
for this purpose?有什么区别,我可以为此目的使用
Mixin
吗?
Your mixin has to be abstract and heritance should come from models.Model i think.你的 mixin 必须是抽象的,并且我认为继承应该来自 models.Model。
class PipedriveSyncRelatedMixin(models.Model):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
class Meta:
abstract = True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.