Performing raw queries

The raw() manager method can be used to perform raw SQL queries that return model instances:

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 ...

Get Mastering Django: Core now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.