[Answered ]-Django Tastypie: Filtering by ForeignKey

2๐Ÿ‘

โœ…

I was able to get it working based on this answer. Iโ€™m listing the final code here for the benefit of others.

from tastypie.resources import ModelResource, fields, ALL_WITH_RELATIONS

from fruits.models import Fruits
from origin.models import Origin

class OriginResource(ModelResource):
    class Meta:
        queryset = Origin.objects.all()
        resource_name = 'origin'
        filtering = {
            "country": ('exact',)
            }

class FruitResource(ModelResource):
    origin = fields.ForeignKey(OriginResource, 'origin', full=True)
    class Meta:
        queryset = Fruits.objects.all()
        allowed_methods = ['get']
        filtering = {
            "origin": ALL_WITH_RELATIONS,
            }

With this code, if I hit http://localhost:8000/api/v1/fruit/?format=json&origin__country=Nepal , I get the following expected output:

{"meta": 
  {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1},
   "objects": [{
         "fruit_name": "Apple", "id": 1, "is_sweet": true, "origin":
         {"country": "Nepal", "id": 3, "resource_uri": ""},
         "quantity": 10, "resource_uri": "/api/v1/fruit/1/"
    }]
}
๐Ÿ‘คDirty Penguin

Leave a comment