Search code examples
pythondjangotastypie

Django tastypie including generic foreign key field results


In Tastypie doc there is an example for generic foreign key usage:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

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

    def __unicode__(self):
        return self.tag

And model resource:

from tastypie.contrib.contenttypes.fields import GenericForeignKeyField
from tastypie.resources import ModelResource

from .models import Note, Quote, TaggedItem


class QuoteResource(ModelResource):

    class Meta:
        resource_name = 'quotes'
        queryset = Quote.objects.all()


class NoteResource(ModelResource):

    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()


class TaggedItemResource(ModelResource):
    content_object = GenericForeignKeyField({
        Note: NoteResource,
        Quote: QuoteResource
    }, 'content_object')

    class Meta:
        resource_name = 'tagged_items'
        queryset = TaggedItem.objects.all()

Now i am able to get results for :

---- > '/api/v1/tagged_items/?note__slug=dadad'

But i could not found a way for including tagged_items into the result of :

----> '/api/v1/note/1/'

?


Solution

  • You will have to add reversed generic field to Note model:

    from django.contrib.contenttypes import generic
    
    class Note(models.Model):
        tags = generic.GenericRelation(TaggedItem)
        [...]
    

    Then add ToManyField to your NoteResource

    class NoteResource(ModelResource):
        tags = fields.ToManyField('myapp.api.resources.TaggedItemResource', 
                                  'tags')
        class Meta:
            resource_name = 'notes'
            queryset = Note.objects.all()
    

    Reverse generic relation doc