In PipedriveSync
model I use GenericForeignKey
so any model can have PipedriveSync
object related.
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. For example user.pipedrivesyncs.all()
Take a look at 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).
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.
Case of specifying pipedrivesyncs
manually:
> u = User.objects.first()
> u.pipedrivesyncs.first()
> <PipedriveSync: PipedriveSync object (20)>
Case when using 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?
Your mixin has to be abstract and heritance should come from models.Model i think.
class PipedriveSyncRelatedMixin(models.Model):
pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync')
class Meta:
abstract = True