Manager.raw(raw_query, params=None, translations=None)
This method takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet
instance. This RawQuerySet
instance can be iterated over just like a normal QuerySet
to provide object instances.
This is best illustrated with an example. Suppose you have the following model:
class Person(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) birth_date = models.DateField(...)
You could then execute custom SQL like so:
>>> for p in Person.objects.raw('SELECT * FROM myapp_person'): ... print(p) John Smith Jane Jones
Of course, this example isn’t very exciting – it’s exactly the same as running Person.objects.all()
. However, raw()
has a bunch of other options that make it very powerful.
Model table names
Where did the name of the Person
table come from in that example?
By default, Django figures out a database table name by joining the model’s “app label” – the name you used in manage.py startapp
– to the model’s class name, with an underscore between them. In the example we’ve assumed that the Person
model lives in an app named myapp
, so its table would be myapp_person
.
For more details check out the documentation for the db_table
option, which also lets you manually set the database table name.
Warning
No checking is done on the SQL statement that is passed in to .raw()
. Django expects that the statement will return a set of rows from the database, but does nothing to enforce that. If the query does not return rows, a (possibly cryptic) error will result.
Warning
If you are performing queries on MySQL, note that MySQL’s silent type coercion may cause unexpected results when mixing types. If you query on a string type column, but with an integer value, MySQL will coerce the types of all values in the table to an integer before performing the comparison. For example, if your table contains the values 'abc'
, 'def'
and you query for WHERE mycolumn=0
, both rows will match. To prevent this, perform the correct typecasting before using the value in a query.
Warning
While a RawQuerySet
instance can be iterated over like a normal QuerySet
, RawQuerySet
doesn’t implement all methods you can use with QuerySet
. For example, __bool__()
and __len__()
are not defined in RawQuerySet
, and thus all RawQuerySet
instances are considered True
. The reason these methods are not implemented in RawQuerySet
is that implementing them without internal caching would be a performance drawback and adding such caching would be backward incompatible.
Please login to continue.