Monday, February 2, 2009

Django Models Tweaks.

I was struggling with joins while using DJango models. After some searching i got some valuable inputs so I have crystallized it according to my understanding.

Let us take an example of a Model - UserDetails which contains other including age and address .
My intention is to query only age and address - then
user_details = UserDetails.objects.all().values('age','address') should return a dictionary of results with keys 'age' and 'address'.
This is easier to compute and I feel that it is a better programming practice to query only the data which we would be processing.

Coming to the issue of joining two Models and displaying a common result.
The first model is the UserDetails Model ( user_details table ) and the UserFoodHabits Model ( user_food_habits table )

user_details = UserDetails.objects.all().extra(tables=['user_food_habits'],where=['user_details.food_habits_id = user_food_habits.id'],select={'habit':user_food_habits.habit, 'habit_type':user_food_habits.type})

Please note that the where clause is written following the raw SQL syntax.

The resulting query set would contain all the attributes of the UserDetails object and additional keys for 'habit' and 'habit_type'. The following piece of code illustrates that.

for user in user_details:
print 'Name %s, Age %s , Habit %s, Type %s ' % (user.name, user.age, user.habit, user.habit_type)

DJango models do not however officialy support group bys and aggregate functions. So it cannot be used with the extra parameter.
But there is a workaround for it :
http://www.evanreiser.com/2009/01/howto-group-by-in-django.html
Apparently DJango 1.1 would have better support for aggregation and stuff !

No comments:

Post a Comment