AVG Decimal simplejson (Decimal is not JSON serializable)

Posted: May 26th, 2010 | Author: | Filed under: Django | Tags: | 4 Comments »

If you use AVG aggregation function on Integer field in MySQL,

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

you will have in a result { “avg_rate” : Decimal(’2.6667′)} and an “Exception Value: Decimal(’2.6667′) is not JSON serializable”.
In this case you can do this:

from django.utils import simplejson
from decimal import Decimal

class MyJSONEncoder(simplejson.JSONEncoder):
    """JSON encoder which understands decimals."""

    def default(self, obj):
        '''Convert object to JSON encodable type.'''
        if isinstance(obj, Decimal):
            return "%d" % obj
        return simplejson.JSONEncoder.default(self, obj)

hotels_json = simplejson.dumps(list(hotels.values()), cls = MyJSONEncoder)

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


Increment/Decrement Field value

Posted: May 26th, 2010 | Author: | Filed under: Django | Tags: | 3 Comments »

Incrementing or decrementing field values can be done by using the F() function.
UPDATE FIELD = FIELD + 1 WHERE… ?

from django.db.models import F

# views.py ...
offer = Offer.objects.get(...)
# SQL: UPDATE field_to_increment = field_to_increment + 1 ...
offer.field_to_increment = F('field_to_increment') + 1
offer.save()

Accessing Request Object In Form

Posted: May 18th, 2010 | Author: | Filed under: Django | Tags: , , | 1 Comment »

Something that I use quite regularly is accessing the request object in a form.

It is actually pretty simple, in your form you add a custom __init__ function that sets the request as a parameter:

class PasswordRecoverForm(PasswordResetForm):
    def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(PasswordRecoverForm, self).__init__(*args, **kwargs)
def clean_email(self):
    """Do something with the request"""
    print self.request

Then in your view code you can pass the request as a parameter.

form = PasswordRecoverForm(request=request)

Change Django Auth Group Ordering

Posted: May 17th, 2010 | Author: | Filed under: Django | Tags: , | No Comments »

Following on from my last post on changing the behaviour of the Django contrib auth models. Another thing you might like to do is to change the default ordering:

from django.contrib.auth.models import User
User._meta.ordering = ['-email']

or

from django.contrib.auth.models import Group
Group._meta.ordering = ['-id']

Django hosting

Posted: May 14th, 2010 | Author: | Filed under: Django | No Comments »

After a month of hard work we are proud to announce that our new django hosting service is up and running!

Django Hosting
The main features include :

  • Live logs
  • manage.py
  • Money back guanrantee
  • Django version switcher
  • Your own domain name
  • 500Mb file storage
  • 100Mb database storage
  • Import code from SVN or GIT

Django Foo hosting