On Sun, Feb 27, 2011 at 5:23 AM, Alexander Bolotnov <[email protected]> wrote: > Is there a way to control json serialization in django? Simple code below > will return serialized object in json: ... > You can see it's serializing it in a way that you are able to re-create the > whole model, shall you want to do this at some point - fair enough, but not > very handy for simple JS ajax in my case: I want bring the traffic to > minimum and make the whole thing little clearer.
You're not the first to propose this. It's a long standing feature request, and yes, we'd like to address it. However, nothing gets built by magic -- someone needs to find the time to devise an API and implement it. There was a recent post on django-dev from someone expressing interest in doing this for the Summer of Code. However, anyone else with an interest is certainly welcome to get involved. > I'm thinking json generating should be part of the model (correct me if I'm > wrong) and done with either native python-json and django implementation but > can't figure how to make it strip the bits that I don't want. This isn't a good idea. Serialization isn't an activity that is unique to models, and JSON isn't the only serialization format. For example, you may want an XML serializer to interface with certain APIs, and you may need an XML serializer and two different JSON serializers in the same project in order to interface with various subsystems. Therefore, serialization needs to be handled independent of the model definition. The approach that we have historically discussed (but not implemented) is to define serialization in two parts: 1) a DSL that defines the rules for an output format -- e.g., which fields will be included, what extra metadata will be included, how deep relations will be traversed. 2) an set of engines that implements the rules of the DSL for a each serialization language. What we have at present is a single implied definition of (1) encoded into (2). > One more thing - even when I restrict it to a set of fields to serialize, it > will keep the id always outside the element container and instead present it > as "pk" outside of it. Yes - which is by design. Django's serializers were designed to allow for dumping and reconstructing data in a database. That means that being able to easily identify the primary key is important. Yours, Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.
