Hey everyone, I'm' working on a basic chained select menu that lets you drill down from county to town to restaurant. The men is populated dynamically using ajax calls from browser to Django on the server side.
It's working as intended, but I'm wondering if there is a "best practice" or convention for returning JSON from Django. My initial Django view built up a JSON response by looping over the results of a database query. A friend who uses a different language/framework then advised that I should avoid building my own JSON responses and instead rely (whenever possible) on JSON libraries or serializers. He said that provides better assurance you'll be sending properly formatted JSON back to the browser. Snippets from both implementations are below, and each worked for my simple use-case. So I'm wondering -- other than the issue raised above, is there a preferred method for generating JSON? Perhaps based on concerns about speed, efficiency or some other factor? Any advice is appreciated. --------------------JSON response built with "manually"----------------- def ajax_parser(request): <<snip>> county = request.GET['param'] towns = Town.objects.filter(county=county) townList = [ ] for town in towns: options = { } options['name'] = "%s" % (town) options['value'] = town.id townList.append(options) <<snip>> -------------------------------------JSON response using serializer--------------------------- def ajax_parser(request): <snip>> if xhr: try: search = request.GET['search'] if search == 'county': #client sends county integer for Town lookup county = request.GET['param'] #generate JSON response for client - primary key becomes Option value and municipality becomes Option text/name data = serializers.serialize("json", Town.objects.filter(county=county), fields=('pk','municipality') ) elif search == 'muni': #client sends muni primary key for Restaurant lookup muni = request.GET['param'] data = serializers.serialize("json", Restaurant.objects.filter(municipality=muni), fields=('pk','name') ) return HttpResponse(data, mimetype='application/json') <<snip>> --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---