On Tue, May 24, 2011 at 8:36 AM, Sells, Fred <fred.se...@adventistcare.org>wrote:
> My code looks like this > > records = models.Residents.objects.extra( where=[....], params=[...]) > data = serializers.serialize('json', records, ensure_ascii=False, > fields=('fname','lname', 'pt')) > return HttpResponse(data) > > After experimenting the "ensure_ascii=False" seems to get rid of the > Unicode prefix which is not used in my work. > > which returns > [ > {"pk": "77777", "model": "app.residents", "fields": {"lname": "Mouse ", > "pt": "0", "fname": "Minnie "}}, > ...] > > I was surprised to see the subnode "fields" in the output. Perhaps I'm > just old school having does basic cgi with json and pretty much forced > the format. > > 1. However is the above the "best practice" or is there an option to > strip the meta data. > I don't think that anyone would condone this as a 'best practice' -- the Django serializers are meant to dump django objects, say into session data, or into database fixtures, and they are really designed to be read by the deserializers when the object needs to be reconstructed. If you are passing data from Django to a browser's JavaScript thread using JSON, then you probably want to either 1. Use an API framework, such as Piston (google: django-piston) or TastyPie (google: django-tastypie) to handle serialization of outgoing data. These are very useful if you expect to be receiving data from the browser in the same format for creating or updating objects, but they can be a lot of overhead for small applications, so you may want to 2. Write your own serialization. It's quite simple, and Django does an excellent job of packaging the simplejson library (deferring to the system installed version, if it's available, and newer than Django's). All you need to do is something like this: from django.utils import simplejson as json ... records = models.Residents.objects.extra( where=[....], params=[...]) data = json.dumps(records.values('fname','lname','pt')) return HttpResponse(data, mimetype='application/json') records.values(...) should return just the dictionary that you want to use. json.dumps(...) will convert that into a JSON string, which you can then return as an HttpResponse. -- Regards, Ian Clelland <clell...@gmail.com> -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.