Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django GenericRelation in model Mixin

I have mixin and model:

class Mixin(object):
    field = GenericRelation('ModelWithGR')

class MyModel(Mixin, models.Model):
   ...

But django do not turn GenericRelation field into GenericRelatedObjectManager:

>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelation>

When I put field into model itself or abstract model - it works fine:

class MyModel(Mixin, models.Model):
   field = GenericRelation('ModelWithGR')

>>> m = MyModel()
>>> m.field
<django.contrib.contenttypes.fields.GenericRelatedObjectManager at 0x3bf47d0>

How can I use GenericRelation in mixin?

like image 754
zymud Avatar asked Jan 23 '15 17:01

zymud


Video Answer


1 Answers

You can always inherit from Model and make it abstract instead of inheriting it from object. Python's mro will figure everything out. Like so:

class Mixin(models.Model):
    field = GenericRelation('ModelWithGR')

    class Meta:
        abstract = True

class MyModel(Mixin, models.Model):
    ...
like image 199
lehins Avatar answered Oct 21 '22 11:10

lehins