django has this complex ORM built in to it, but after spending much time on it, it is still hard for me to make queries that are remarkably simple in SQL. There are even some simple things that I can’t find a way to do through the django ORM (e.g. ‘select distinct column1 from tablename’).
Is there any documentation that shows “For common SQL statements, here is how you do it in django”?
(I did try google first, but either it isn’t out there or I just can’t think of the right query…)
There are some things that are ridiculously simple in SQL that are difficult or impossible through an ORM. This is called the “object-relational impedance mismatch.” Essentially an ORM treats each row in a database as a separate object. So operations that involve treating values separately from their row become fairly challenging. Recent versions of Django (1.1+) improve this situation somewhat with aggregation support, but for many things, only SQL will work.
To this end, django provides several methods of letting you drop down into raw sql quite simply. Some of them return model objects as results, while others take you all the way down to your DBAPI2 connector. The most low level looks like this:
If you want to return a queryset from a SQL query, use the raw() on your model’s manager:
Note: raw() is only available in the development version of Django, which should be merged into trunk as of 1.2.
Complete information is available in the documentation under Performing raw SQL queries.