Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 216
Mirage Avatar asked Nov 09 '12 02:11

Mirage


1 Answers

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.

like image 193
Blake Avatar answered Oct 21 '22 08:10

Blake