开发者

Deep JSON Serialization of Django objects

开发者 https://www.devze.com 2022-12-21 17:41 出处:网络
Consider the following Django Model: class Event(models.Model): startDate = models.DateField() endDate = models.DateField()

Consider the following Django Model:

class Event(models.Model):

    startDate = models.DateField()
    endDate = models.DateField()

    user = models开发者_JS百科.ForeignKey(User, null=True)

Later in my view I do this:

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

And get the following response:

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

Is it possible for to get the serializer to 'go deeper' and serialize the User that is referenced by the Event instance so I can access that data in my Javascript code?

It seems as if this is possible using the development version, but I'm using 1.1 FWIW.


This might help you out: http://wadofstuff.blogspot.com/2009/02/django-full-serializers-part-i.html


django-tastypie will do the trick. It has all kinds of support for deep relations like that, as well as adhering to REST, meaning if you use jQuery, a simple $.ajax() will do the trick to get the data.

Because tastypie adheres to REST, it also has support for updates, inserts, and deletes using PUT, POST, and DELETE methods, respectively.

It supports JSON, XML, and YAML as well. It helps build out a full REST API, which might seem a bit obtuse for what you're trying to do, but it's pretty easy to get set up, and lets you fully customize what fields get 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 won't come back formatted exactly as you specified, but it is easily configured, and adheres to a web standard, which becomes markedly more useful as your project grows.

0

精彩评论

暂无评论...
验证码 换一张
取 消