How to load foreign key elements in Tastypie

In my Django model, I have 10 fields, and there are 3 fields that are foreign keys. In my JSON data obtained from a GET request, I get all fields, but not foreign keys.

I also did this, but I still do not get these fields in 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 a field in a model like city , but this field is not available in the JSON that I get from it.

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

If I do this, then I will get the city, but can I do this without a definition:

 def dehydrate(self, bundle): bundle.data["city_name"] = bundle.obj.city__name return bundle 
+7
source share
1 answer

You will want to create related resources for your foreign key fields and paste them into MyResource . If you create an embedded resource full=True , it will dehydrate it when you retrieve MyResource , otherwise it will insert it as a linked uri resource.

 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 a GET request to MyResource .


If you just want to get the field returned by the __unicode__ model, you can try to do the following (rather than embed the related resource):

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

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

+11
source

All Articles