Extra Select field in JSON

Posted: March 31st, 2010 | Author: ekaterina | Filed under: Django | Tags: , | 2 Comments »

Fields from extra select query

hotels = Hotel.objects.filter(city = "Paris").extra(
    select={
        'review_count': 'SELECT COUNT(*) FROM hotel_review WHERE hotel_review.is_active = 1 AND hotel_review.hotel_id = hotel_hotel.id',
    },
)

could be used in templates:

{% for hotel in hotels %}
    {{hotel.name}} has {{hotel.review_count}} reviews
{% endfor %}

But when you try to serialize hotels QuerySet, you will have only fields from model and you won’t be able to access extra select field named “review_count” in resulting JSON file.

The solution is to serialize hotels.value() object:

from django.utils import simplejson

hotels_json = simplejson.dumps(list(hotels.values()))

And your JSON will include “review_count” field. It will look like this:

[
   {
      "name":"Hilton",
      "city":"Paris",
      "review_count":3
   }
]

2 Comments on “Extra Select field in JSON”

  1. 1 Filter annotate() COUNT() | Django foo said at 4:43 pm on March 31st, 2010:

    [...] How to use review_count parameter in template and JSON objects see article about Extra Select Field in JSON [...]

  2. 2 AVG Decimal simplejson (Decimal is not JSON serializable) | Django foo said at 11:46 am on May 26th, 2010:

    [...] You can read about extra search fields and JSON serialization in our article [...]


Leave a Reply