Django tastypie save reverse GenericForeignKeyField

182 views Asked by At

Django Tastypie can save related objects even with reverse relationship.

But is it able for Django Tastypie to save reverse relationship of GenericForeignKeyField?

My resources (not full, but the important only),

class AreaResource(ModelResource):
    tripl3user = fields.ManyToManyField(
        'tripl3sales.api.resources.area.Tripl3UserResource',
        'tripl3user',
        related_name='area',
        full=True
    )

class Tripl3UserResource(ModelResource):
    content_type = fields.ForeignKey(
        'tripl3sales.api.resources.contenttype.ContentTypeResource',
        'content_type'
    )
    content_object = GenericForeignKeyField({
        Area : AreaResource
        }, 'content_object')

My models.py,

class Area(models.Model):
    name = models.CharField(max_length=50, unique=True)
    tripl3user = generic.GenericRelation('Tripl3User')

class Tripl3User(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

Is it possible to save reverse relationship of generic foreign key? If so, then how to do it? What does the data look like?

1

There are 1 answers

0
adityasdarma1 On

Finally I got the answer.

In a resource that has content_type and object_id, there is no need to declare content_type because content_object is enough. And for related_name, instead of using area, we use content_object.

So, my resources.py should be,

class AreaResource(ModelResource):
    tripl3user = fields.ManyToManyField(
        'tripl3sales.api.resources.area.Tripl3UserResource',
        'tripl3user',
        related_name='content_object',
        full=True
    )

class Tripl3UserResource(ModelResource):
    content_object = GenericForeignKeyField({
        Area : AreaResource
    }, 'content_object')

Hope this will help others.