How to add an extra object to a delicious pie return json in python django

In a Django project, I get two objects when I get a JSON response

data.meta and data.objects

This is my resource.

 class MyResource(ModelResource): def dehydrate(self, bundle): bundle.data["absolute_url"] = bundle.obj.get_absolute_url() bundle.data['myfields'] = MyDataFields return bundle class Meta: queryset = MyData.objects.all() resource_name = 'weather' serializer = Serializer(formats=['json']) ordering = MyDataFields 

now i want another field in json like

data.myfields

but if I do it above, this field is added to each object, for example

data.objects.myfields

how can i do data.myfields

+7
source share
2 answers

One way to do this is to override the Tastypie ModelResource get_list .

 import json from django.http import HttpResponse ... class MyResource(ModelResource): ... def get_list(self, request, **kwargs): resp = super(MyResource, self).get_list(request, **kwargs) data = json.loads(resp.content) data['myfields'] = MyDataFields data = json.dumps(data) return HttpResponse(data, content_type='application/json', status=200) 
+4
source

IMHO's best approach is to use alter_list_data_to_serialize , a function made to override / add fields to data before making an answer:

  def alter_list_data_to_serialize(self, request, data): data['meta']['current_time'] = datetime.strftime(datetime.utcnow(), "%Y/%m/%d") return data 

This way, you will not override the entire mimetype / status code for all calls and will not be cleaner.

+18
source

All Articles