How to add extra object to tasty pie return json in python django
Asked Answered
S

2

8

In Django project i get two objects when i receive the 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 to other field in json like

data.myfields

but if i do the above way then that field is added to every object like

data.objects.myfields

how can i do data.myfields

Sportswoman answered 9/11, 2012 at 4:46 Comment(0)
L
4

One way to do this is by overriding Tastypie ModelResource's get_list method.

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)
Lp answered 9/11, 2012 at 5:38 Comment(0)
B
20

a better approach IMHO would be to use alter_list_data_to_serialize, the function made to override/add fields to the data before making the response:

    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 don't override all the mimetype/status code for all calls and it's cleaner.

Bracelet answered 30/4, 2013 at 15:54 Comment(2)
Thanks ! I used that to add bounding box from a GeoDjango query: data['extent'] = self._meta.queryset.extent()Chiropteran
Thanks a lot this saved me lot of time and effort!Cop
L
4

One way to do this is by overriding Tastypie ModelResource's get_list method.

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)
Lp answered 9/11, 2012 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.