Django GenericRelation in model Mixin
Asked Answered
R

1

7

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?

Righthanded answered 23/1, 2015 at 17:17 Comment(1)
Could something like this help? timmyomahony.com/blog/…Trincomalee
L
6

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):
    ...
Loisloise answered 27/1, 2015 at 3:54 Comment(2)
I know. In question I wrote 'When I put field into model itself or abstract model - it works fine'. The question is about mixin only.Righthanded
You cannot use fields on regular objects in the same way they are used on Models, especially related ones. All because there is special logic applied upon model class creation, which deals with fields attached to it in special ways, depending on a field type: github.com/django/django/blob/master/django/db/models/… You can try to figure something out, but without some weird hacks it won't be possible. So I wouldn't even recommend doing that.Loisloise

© 2022 - 2024 — McMap. All rights reserved.