On Tuesday 01 September 2009 12:29:56 pm Amir Habibi wrote:
> How can I serialize a Queryset along with the related records. For
> example, in Poll and Choice case, I need each poll to have the choices
> encoded in json format.
>
> Thanks
>

you'll want to look at the docs on serialization [1], it is pretty straight 
forward, though the examples use 'xml', it does output to json data (among 
other formats) also.

http://docs.djangoproject.com/en/dev/topics/serialization/

It's quite simple to use, in my examples I'm using FAQ Categories and Question 
and Answers within a category.

In [1]: from django.core import serializers

In [2]: from base.models import FAQC
FAQCategory         FAQCategoryManager  

In [2]: from base.models import FAQCategory, FAQ
FAQ                 FAQCategory         FAQCategoryManager  

In [2]: from base.models import FAQCategory, FAQ

In [3]: cat = FAQ
FAQ          FAQCategory  

In [3]: cat = FAQCategory.objects.all().get(pk=1)

In [4]: cat
Out[4]: <FAQCategory: General Questions>

In [5]: faqs = FAQ.objects.all().filter(category=cat)

In [6]: faqs
Out[6]: [<FAQ: General Questions - 1. Why?>]

In [7]: json = serializers.serialize('json', faqs)

In [8]: json
Out[8]: '[{"pk": 1, "model": "base.faq", "fields": {"answer": "Because I want 
to.", "category": 1, "question": "Why?", "number": 1, "slug": "why"}}]'

you can also extend HttpResponse to return a JsonResponse:

# as seen on: http://toys.jacobian.org/presentations/2007/oscon/tutorial/#s67
class JSONResponse(HttpResponse):
  def __init__(self, data):
    HttpResponse.__init__(self, data, mimetype="application/json")

In your view code just return this, using the serialized data from above:

def ajaxview(request):
        cat = FAQCategory.objects.all().get(pk=1)
        faqs = FAQ.objects.all().filter(category=cat)
        json = serializers.serialize('json', faqs)
        return JSONResponse(json)

hope this helps,

Mike
-- 
War is peace.  Freedom is slavery.  Ketchup is a vegetable.

Attachment: signature.asc
Description: This is a digitally signed message part.

Reply via email to