Deep JSON Serializing Django Objects

Consider the following Django model:

class Event(models.Model): startDate = models.DateField() endDate = models.DateField() user = models.ForeignKey(User, null=True) 

Later, in my opinion, I do this:

 django.core.serializers.serialize("json", Event.objects.all()) return HttpResponse(data, mimetype='application/javascript') 

And get the following answer:

 [ { "pk": 1, "model": "myapp.event", "fields": { "startDate": "2010-02-02", "endDate": "2010-02-02", "user": 2 } } ] 

Is it possible to make the serializer β€œdeeper” and serialize the user referenced by the Event instance so that I can access this data in my Javascript code?

This seems to be possible using the development version, but I am using 1.1 FWIW.

+4
source share
2 answers

django-tastypie will do the trick. It has all kinds of support for such deep relationships, and also adheres to REST, which means that if you use jQuery, a simple $.ajax() will do the trick to get the data.

Since tastypie adheres to REST, it also supports updates, inserts, and deletes using the PUT , POST and DELETE methods, respectively.

It supports JSON, XML and YAML. This helps to create a complete REST API that may seem a little dumb for what you are trying to do, but it is pretty easy to configure, and allows you to fully customize which fields are returned and which fields are excluded.

In your API, you would do something like:

 from tastypie.resources import Resource from django.contrib.auth.models import User from myapp import models class UserResource(Resource): class Meta: queryset = User.objects.all() resource_name = 'user' class EventResource(Resource): user = fields.ToOneField(UserResource, full=True) class Meta: queryset = models.Event.objects.all() resource_name = 'event' 

This will not return in a formatted form exactly as you indicated, but it is easy to configure and adheres to the web standard, which becomes much more useful as your project grows.

0
source

Source: https://habr.com/ru/post/1303069/


All Articles