Question

I am using django-taggit for tagging. I have django-tastypie REST resource for the same object.

While exposing the REST resource, it doesn't fetch the tag field(e.g. equivalent to model.tags.all()).

Is there anything special needs to be done?

I wanted to perform GET and POST operation on object model and retrieve and insert the tags.

Can some one please point to the sample setup to return the tag objects? I have referred to gist here, however not able to understand that how you can retrieve associated tags when querying model.

Thanks for you help.

Was it helpful?

Solution

First make a TagResource :

from taggit.models import Tag

class TagResource(ModelResource):
    class Meta:
        queryset = Tag.objects.all()

Then in your resource that got tags:

class FooResource(ModelResource):

    tags = fields.ToManyField(TagResource, 'tags', # if your tag field is 'tags'
                              full = True)

    class Meta:
        queryset = Foo.objects.all()

It should work.

UPDATE

In order to filter the tag, you have to filter it through TagResource, assuming your api name is v1, the url is :

/api/v1/tag/?slug=anytagyouwant&format=json

Above url is for like : 'is anytagyouwant exist?'

for 'get all foo that have anytagyouwant tag'

/api/v1/foo/?tags__slug=anytagyouwant&format=json

Note, to be able to filter for certain fields, you have to declare it in your resource, using FooResource as an example :

from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS

class FooResource(ModelResource):

    tags = fields.ToManyField(TagResource, 'tags', # if your tag field is 'tags'
                              full = True)

    class Meta:
        queryset = Foo.objects.all()
        filtering = dict(
            tags = ALL,
            # or 
            tags = ALL_WITH_RELATIONS,
        )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top