Search code examples
pythondjangotastypie

How to load the foreign keys elements in Tastypie


In my Django model, I have 10 fields and there are 3 fields which are foreign keys. In my JSON data which is received from a GET request, I am getting all the fields but not the foreign keys.

I have also done this, but I am still not getting those fields in the JSON data:

DataFields = MyData._meta.get_all_field_names()
class MyResource(ModelResource):
       class Meta:
        queryset = MyData.objects.all()
        resource_name = 'Myres'
        serializer = Serializer(formats=['json'])
        filtering = dict(zip(DataFields, [ALL_WITH_RELATIONS for f in DataFields]))

For example, I have the field in model like city, but that field is not available in the JSON I get from it.

Is there any way that in JSON I can get city:city__name automatically?

If I do this, then I get the city, but can I do that without defining:

def dehydrate(self, bundle):
        bundle.data["city_name"] = bundle.obj.city__name
        return bundle

Solution

  • You'll want to create related resources for your foreign key fields and embed them in MyResource. If you make the embedded resource full=True, it'll dehydrate it when fetching MyResource, otherwise it'll embed it as the related resource uri.

    class RelatedResource(ModelResource):
        class Meta:
            ...
    
    
    class MyResource(ModelResource):
        related = fields.ForeignKey(RelatedResource, full=True)
    
        class Meta:
            ...
    

    You can then filter by ?related__field=value in the GET request to MyResource.


    If you're just wanting the field returned by the model's __unicode__, you can try doing the following (rather than embedding a related resource):

    class MyResource(ModelResource):    
        city = fields.CharField(attribute="city")
    
        class Meta:
            ...
    

    Where "city" is the field name of the foreign key on the MyData model.