Django only

Django only DEFAULT


Disable Django database writes.


Python 3.6 to 3.10 supported.

Django 2.2 to 4.0 supported.

Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Install with pip:

python -m pip install django-read-only

Then add to your installed apps:

INSTALLED_APPS= [ ..., "django_read_only", ..., ]


In your settings file, set to and all data modification queries will cause an exception:

$ DJANGO_READ_ONLY=1 python shell...>>> User.objects.create_user(username="hacker", password="hunter2")...DjangoReadOnlyError(...)

For convenience, you can also control this with the environment variable, which will count as if set to anything but the empty string. The setting takes precedence over the environment variable.

During a session with set on, you can re-enable writes by calling :

>>> import django_read_only >>> django_read_only.enable_writes()

Writes can be disabled with :

>>> django_read_only.disable_writes()

To temporarily allow writes, use the context manager / decorator:

>>> with django_read_only.temp_writes(): ... User.objects.create_user(...) ...

Note that writes being enabled/disabled is global state, affecting all threads and asynchronous coroutines.

Recommended Setup

Set read-only mode on in your production environment, and maybe staging, during interactive sessions. This can be done by setting the environment variable in the shell profile file (, , etc.) of the system’s user account. This way developers performing exploratory queries can’t accidentally make changes, but writes will remain enabled for non-shell processes like your WSGI server.

With this setup, developers can also run management commands with writes enabled by setting the environment variable before the command:

$ DJANGO_READ_ONLY= python clearsessions

Some deployment platforms don’t allow you to customize your shell profile files. In this case, you will need to find a way to detect shell mode from within your settings file.

For example, on Heroku there’s the environment variable (docs) to identify the current virtual machine. It starts with “run.” for interactive sessions. You can use this to enable read-only mode in your settings file like so:

ifos.environ.get("DYNO", "").startswith("run."): DJANGO_READ_ONLY=bool(os.environ.get("DJANGO_READ_ONLY", "1")) else: DJANGO_READ_ONLY=False

How it Works

The most accurate way to prevent writes is to connect as a separate database user with only read permission. However, this has limitations - Django doesn’t support modifying the setting live, so sessions would not be able to temporarily allow writes.

Instead, django-read-only uses always installed database instrumentation to inspect executed queries and only allow those which look like reads. It uses a “fail closed” philosophy, so anything unknown will fail, which should be fairly reasonable.

Because django-read-only uses Django database instrumentation, it cannot block queries running through the underlying database connection (accesses through ), and it cannot filter operations within stored procedures (which use ). These are very rare in practice though, so django-read-only’s method works well for most projects.



Methods that return new s¶

Django provides a range of refinement methods that modify either the types of results returned by the or the way its SQL query is executed.


Returns a new containing objects that match the given lookup parameters.

The lookup parameters () should be in the format described in Field lookups below. Multiple parameters are joined via in the underlying SQL statement.

If you need to execute more complex queries (for example, queries with statements), you can use .


Returns a new containing objects that do not match the given lookup parameters.

The lookup parameters () should be in the format described in Field lookups below. Multiple parameters are joined via in the underlying SQL statement, and the whole thing is enclosed in a .

This example excludes all entries whose is later than 2005-1-3 AND whose is “Hello”:


In SQL terms, that evaluates to:


This example excludes all entries whose is later than 2005-1-3 OR whose headline is “Hello”:


In SQL terms, that evaluates to:


Note the second example is more restrictive.

If you need to execute more complex queries (for example, queries with statements), you can use .

(*args, **kwargs

Annotates each object in the with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or an aggregate expression (averages, sums, etc.) that has been computed over the objects that are related to the objects in the .

Each argument to is an annotation that will be added to each object in the that is returned.

The aggregation functions that are provided by Django are described in Aggregation Functions below.

Annotations specified using keyword arguments will use the keyword as the alias for the annotation. Anonymous arguments will have an alias generated for them based upon the name of the aggregate function and the model field that is being aggregated. Only aggregate expressions that reference a single field can be anonymous arguments. Everything else must be a keyword argument.

For example, if you were manipulating a list of blogs, you may want to determine how many entries have been made in each blog:

>>> fromdjango.db.modelsimportCount>>> q=Blog.objects.annotate(Count('entry'))# The name of the first blog>>> q[0].name'Blogasaurus'# The number of entries on the first blog>>> q[0].entry__count42

The model doesn’t define an attribute by itself, but by using a keyword argument to specify the aggregate function, you can control the name of the annotation:

>>> q=Blog.objects.annotate(number_of_entries=Count('entry'))# The number of entries on the first blog, using the name provided>>> q[0].number_of_entries42

For an in-depth discussion of aggregation, see the topic guide on Aggregation.

(*args, **kwargs

Same as , but instead of annotating objects in the , saves the expression for later reuse with other methods. This is useful when the result of the expression itself is not needed but it is used for filtering, ordering, or as a part of a complex expression. Not selecting the unused value removes redundant work from the database which should result in better performance.

For example, if you want to find blogs with more than 5 entries, but are not interested in the exact number of entries, you could do this:

>>> fromdjango.db.modelsimportCount>>> blogs=Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)

can be used in conjunction with , , , , and . To use aliased expression with other methods (e.g. ), you must promote it to an annotation:


and can take expressions directly, but expression construction and usage often does not happen in the same place (for example, method creates expressions, for later use in views). allows building complex expressions incrementally, possibly spanning multiple methods and modules, refer to the expression parts by their aliases and only use for the final result.


By default, results returned by a are ordered by the ordering tuple given by the option in the model’s . You can override this on a per- basis by using the method.



The result above will be ordered by descending, then by ascending. The negative sign in front of indicates descending order. Ascending order is implied. To order randomly, use , like so:


Note: queries may be expensive and slow, depending on the database backend you’re using.

To order by a field in a different model, use the same syntax as when you are querying across model relations. That is, the name of the field, followed by a double underscore (), followed by the name of the field in the new model, and so on for as many models as you want to join. For example:


If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model, or order by the related model’s primary key if there is no specified. For example, since the model has no default ordering specified:


…is identical to:


If had , then the first queryset would be identical to:


You can also order by query expressions by calling or on the expression:


and have arguments ( and ) that control how null values are sorted.

Be cautious when ordering by fields in related models if you are also using . See the note in for an explanation of how related model ordering can change the expected results.


It is permissible to specify a multi-valued field to order the results by (for example, a field, or the reverse relation of a field).

Consider this case:


Here, there could potentially be multiple ordering data for each ; each with multiple will be returned multiple times into the new that creates. In other words, using on the could return more items than you were working on to begin with - which is probably neither expected nor useful.

Thus, take care when using multi-valued field to order the results. If you can be sure that there will only be one ordering piece of data for each of the items you’re ordering, this approach should not present problems. If not, make sure the results are what you expect.

There’s no way to specify whether ordering should be case sensitive. With respect to case-sensitivity, Django will order results however your database backend normally orders them.

You can order by a field converted to lowercase with which will achieve case-consistent ordering:


If you don’t want any ordering to be applied to a query, not even the default ordering, call with no parameters.

You can tell if a query is ordered or not by checking the attribute, which will be if the has been ordered in any way.

Each call will clear any previous ordering. For example, this query will be ordered by and not :



Ordering is not a free operation. Each field you add to the ordering incurs a cost to your database. Each foreign key you add will implicitly include all of its default orderings as well.

If a query doesn’t have an ordering specified, results are returned from the database in an unspecified order. A particular ordering is guaranteed only when ordering by a set of fields that uniquely identify each object in the results. For example, if a field isn’t unique, ordering by it won’t guarantee objects with the same name always appear in the same order.


Use the method to reverse the order in which a queryset’s elements are returned. Calling a second time restores the ordering back to the normal direction.

To retrieve the “last” five items in a queryset, you could do this:


Note that this is not quite the same as slicing from the end of a sequence in Python. The above example will return the last item first, then the penultimate item and so on. If we had a Python sequence and looked at , we would see the fifth-last item first. Django doesn’t support that mode of access (slicing from the end), because it’s not possible to do it efficiently in SQL.

Also, note that should generally only be called on a which has a defined ordering (e.g., when querying against a model which defines a default ordering, or when using ). If no such ordering is defined for a given , calling on it has no real effect (the ordering was undefined prior to calling , and will remain undefined afterward).


Returns a new that uses in its SQL query. This eliminates duplicate rows from the query results.

By default, a will not eliminate duplicate rows. In practice, this is rarely a problem, because simple queries such as don’t introduce the possibility of duplicate result rows. However, if your query spans multiple tables, it’s possible to get duplicate results when a is evaluated. That’s when you’d use .


Any fields used in an call are included in the SQL columns. This can sometimes lead to unexpected results when used in conjunction with . If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.

Similarly, if you use a query to restrict the columns selected, the columns used in any (or default model ordering) will still be involved and may affect uniqueness of the results.

The moral here is that if you are using be careful about ordering by related models. Similarly, when using and together, be careful when ordering by fields not in the call.

On PostgreSQL only, you can pass positional arguments () in order to specify the names of fields to which the should apply. This translates to a SQL query. Here’s the difference. For a normal call, the database compares each field in each row when determining which rows are distinct. For a call with specified field names, the database will only compare the specified field names.


When you specify field names, you must provide an in the , and the fields in must start with the fields in , in the same order.

For example, gives you the first row for each value in column . If you don’t specify an order, you’ll get some arbitrary row.

Examples (those after the first will only work on PostgreSQL):

>>> Author.objects.distinct()[...]>>> Entry.objects.order_by('pub_date').distinct('pub_date')[...]>>> Entry.objects.order_by('blog').distinct('blog')[...]>>> Entry.objects.order_by('author','pub_date').distinct('author','pub_date')[...]>>> Entry.objects.order_by('blog__name','mod_date').distinct('blog__name','mod_date')[...]>>> Entry.objects.order_by('author','pub_date').distinct('author')[...]


Keep in mind that uses any default related model ordering that has been defined. You might have to explicitly order by the relation or referenced field to make sure the expressions match those at the beginning of the clause. For example, if the model defined an by :


…wouldn’t work because the query would be ordered by thus mismatching the expression. You’d have to explicitly order by the relation field ( in this case) or the referenced one () to make sure both expressions match.

(*fields, **expressions

Returns a that returns dictionaries, rather than model instances, when used as an iterable.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

This example compares the dictionaries of with the normal model objects:

# This list contains a Blog object.>>>Blog.objects.filter(name__startswith='Beatles')<QuerySet[<Blog:BeatlesBlog>]># This list contains a dictionary.>>>Blog.objects.filter(name__startswith='Beatles').values()<QuerySet[{'id':1,'name':'Beatles Blog','tagline':'All the latest Beatles news.'}]>

The method takes optional positional arguments, , which specify field names to which the should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table.


>>> Blog.objects.values()<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>>>> Blog.objects.values('id','name')<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

The method also takes optional keyword arguments, , which are passed through to :

>>> fromdjango.db.models.functionsimportLower>>> Blog.objects.values(lower_name=Lower('name'))<QuerySet [{'lower_name': 'beatles blog'}]>

You can use built-in and custom lookups in ordering. For example:

>>> fromdjango.db.modelsimportCharField>>> fromdjango.db.models.functionsimportLower>>> CharField.register_lookup(Lower)>>> Blog.objects.values('name__lower')<QuerySet [{'name__lower': 'beatles blog'}]>

An aggregate within a clause is applied before other arguments within the same clause. If you need to group by another value, add it to an earlier clause instead. For example:

>>> fromdjango.db.modelsimportCount>>> Blog.objects.values('entry__authors',entries=Count('entry'))<QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>>>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))<QuerySet [{'entry__authors': 1, 'entries': 33}]>

A few subtleties that are worth mentioning:

  • If you have a field called that is a , the default call will return a dictionary key called , since this is the name of the hidden model attribute that stores the actual value (the attribute refers to the related model). When you are calling and passing in field names, you can pass in either or and you will get back the same thing (the dictionary key will match the field name you passed in).

    For example:

    >>> Entry.objects.values()<QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>>>> Entry.objects.values('blog')<QuerySet [{'blog': 1}, ...]>>>> Entry.objects.values('blog_id')<QuerySet [{'blog_id': 1}, ...]>
  • When using together with , be aware that ordering can affect the results. See the note in for details.

  • If you use a clause after an call, any fields defined by a argument in the must be explicitly included in the call. Any call made after a call will have its extra selected fields ignored.

  • Calling and after doesn’t make sense, so doing so will raise a .

  • Combining transforms and aggregates requires the use of two calls, either explicitly or as keyword arguments to . As above, if the transform has been registered on the relevant field type the first can be omitted, thus the following examples are equivalent:

    >>> fromdjango.db.modelsimportCharField,Count>>> fromdjango.db.models.functionsimportLower>>> CharField.register_lookup(Lower)>>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>>>> Blog.objects.values(... entry__authors__name__lower=Lower('entry__authors__name')... ).annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>>>> Blog.objects.annotate(... entry__authors__name__lower=Lower('entry__authors__name')... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>

It is useful when you know you’re only going to need values from a small number of the available fields and you won’t need the functionality of a model instance object. It’s more efficient to select only the fields you need to use.

Finally, note that you can call , , etc. after the call, that means that these two calls are identical:


The people who made Django prefer to put all the SQL-affecting methods first, followed (optionally) by any output-affecting methods (such as ), but it doesn’t really matter. This is your chance to really flaunt your individualism.

You can also refer to fields on related models with reverse relations through , and attributes:

>>> Blog.objects.values('name','entry__headline')<QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'}, {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>


Because attributes and reverse relations can have multiple related rows, including these can have a multiplier effect on the size of your result set. This will be especially pronounced if you include multiple such fields in your query, in which case all possible combinations will be returned.

Boolean values for on SQLite

Due to the way the SQL function is implemented on SQLite, will return and instead of and for key transforms.

(*fields, flat=False, named=False

This is similar to except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the call — so the first item is the first field, etc. For example:

>>> Entry.objects.values_list('id','headline')<QuerySet [(1, 'First entry'), ...]>>>> fromdjango.db.models.functionsimportLower>>> Entry.objects.values_list('id',Lower('headline'))<QuerySet [(1, 'first entry'), ...]>

If you only pass in a single field, you can also pass in the parameter. If , this will mean the returned results are single values, rather than one-tuples. An example should make the difference clearer:

>>> Entry.objects.values_list('id').order_by('id')<QuerySet[(1,), (2,), (3,), ...]>>>> Entry.objects.values_list('id',flat=True).order_by('id')<QuerySet [1, 2, 3, ...]>

It is an error to pass in when there is more than one field.

You can pass to get results as a :

>>> Entry.objects.values_list('id','headline',named=True)<QuerySet [Row(id=1, headline='First entry'), ...]>

Using a named tuple may make use of the results more readable, at the expense of a small performance penalty for transforming the results into a named tuple.

If you don’t pass any values to , it will return all the fields in the model, in the order they were declared.

A common need is to get a specific field value of a certain model instance. To achieve that, use followed by a call:

>>> Entry.objects.values_list('headline',flat=True).get(pk=1)'First entry'

and are both intended as optimizations for a specific use case: retrieving a subset of data without the overhead of creating a model instance. This metaphor falls apart when dealing with many-to-many and other multivalued relations (such as the one-to-many relation of a reverse foreign key) because the “one row, one object” assumption doesn’t hold.

For example, notice the behavior when querying across a :

>>> Author.objects.values_list('name','entry__headline')<QuerySet [('Noam Chomsky', 'Impressions of Gaza'), ('George Orwell', 'Why Socialists Do Not Believe in Fun'), ('George Orwell', 'In Defence of English Cooking'), ('Don Quixote', None)]>

Authors with multiple entries appear multiple times and authors without any entries have for the entry headline.

Similarly, when querying a reverse foreign key, appears for entries not having any author:

>>> Entry.objects.values_list('authors')<QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>

Boolean values for on SQLite

Due to the way the SQL function is implemented on SQLite, will return and instead of and for key transforms.

(field, kind, order='ASC'

Returns a that evaluates to a list of objects representing all available dates of a particular kind within the contents of the .

should be the name of a of your model. should be either , , , or . Each object in the result list is “truncated” to the given .

  • returns a list of all distinct year values for the field.
  • returns a list of all distinct year/month values for the field.
  • returns a list of all distinct year/week values for the field. All dates will be a Monday.
  • returns a list of all distinct year/month/day values for the field.

, which defaults to , should be either or . This specifies how to order the results.


>>> Entry.objects.dates('pub_date','year')[, 1, 1)]>>> Entry.objects.dates('pub_date','month')[, 2, 1),, 3, 1)]>>> Entry.objects.dates('pub_date','week')[, 2, 14),, 3, 14)]>>> Entry.objects.dates('pub_date','day')[, 2, 20),, 3, 20)]>>> Entry.objects.dates('pub_date','day',order='DESC')[, 3, 20),, 2, 20)]>>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date','day')[, 3, 20)]

(field_name, kind, order='ASC', tzinfo=None, is_dst=None

Returns a that evaluates to a list of objects representing all available dates of a particular kind within the contents of the .

should be the name of a of your model.

should be either , , , , , , or . Each object in the result list is “truncated” to the given .

, which defaults to , should be either or . This specifies how to order the results.

defines the time zone to which datetimes are converted prior to truncation. Indeed, a given datetime has different representations depending on the time zone in use. This parameter must be a object. If it’s , Django uses the current time zone. It has no effect when is .

indicates whether or not should interpret nonexistent and ambiguous datetimes in daylight saving time. By default (when ), raises an exception for such datetimes.

New in Django 3.1:

The parameter was added.


This function performs time zone conversions directly in the database. As a consequence, your database must be able to interpret the value of . This translates into the following requirements:


Calling will create a queryset that never returns any objects and no query will be executed when accessing the results. A queryset is an instance of .


>>> Entry.objects.none()<QuerySet []>>>> fromdjango.db.models.queryimportEmptyQuerySet>>> isinstance(Entry.objects.none(),EmptyQuerySet)True


Returns a copy of the current (or subclass). This can be useful in situations where you might want to pass in either a model manager or a and do further filtering on the result. After calling on either object, you’ll definitely have a to work with.

When a is evaluated, it typically caches its results. If the data in the database might have changed since a was evaluated, you can get updated results for the same query by calling on a previously evaluated .

(*other_qs, all=False

Uses SQL’s operator to combine the results of two or more s. For example:

>>> qs1.union(qs2,qs3)

The operator selects only distinct values by default. To allow duplicate values, use the argument.

, , and return model instances of the type of the first even if the arguments are s of other models. Passing different models works as long as the list is the same in all s (at least the types, the names don’t matter as long as the types are in the same order). In such cases, you must use the column names from the first in methods applied to the resulting . For example:

>>> qs1=Author.objects.values_list('name')>>> qs2=Entry.objects.values_list('headline')>>> qs1.union(qs2).order_by('name')

In addition, only , , , , and specifying columns (i.e. slicing, , , , and /) are allowed on the resulting . Further, databases place restrictions on what operations are allowed in the combined queries. For example, most databases don’t allow or in the combined queries.


Uses SQL’s operator to return the shared elements of two or more s. For example:

>>> qs1.intersection(qs2,qs3)

See for some restrictions.


Uses SQL’s operator to keep only elements present in the but not in some other s. For example:

>>> qs1.difference(qs2,qs3)

See for some restrictions.


Returns a that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.

The following examples illustrate the difference between plain lookups and lookups. Here’s standard lookup:

# Hits the database.e=Entry.objects.get(id=5)# Hits the database again to get the related Blog

And here’s lookup:

# Hits the database.e=Entry.objects.select_related('blog').get(id=5)# Doesn't hit the database, because has been prepopulated# in the previous

You can use with any queryset of objects:

fromdjango.utilsimporttimezone# Find all the blogs with entries scheduled to be published in the future.blogs=set()foreinEntry.objects.filter('blog'):# Without select_related(), this would make a database query for each# loop iteration in order to fetch the related blog for each entry.blogs.add(

The order of and chaining isn’t important. These querysets are equivalent:


You can follow foreign keys in a similar way to querying them. If you have the following models:

fromdjango.dbimportmodelsclassCity(models.Model):# ...passclassPerson(models.Model):# ...hometown=models.ForeignKey(City,on_delete=models.SET_NULL,blank=True,null=True,)classBook(models.Model):#,on_delete=models.CASCADE)

… then a call to will cache the related and the related :

# Hits the database with joins to the author and hometown tables.b=Book.objects.select_related('author__hometown').get(id=4) Doesn't hit the database.c=p.hometown# Doesn't hit the database.# Without select_related()...b=Book.objects.get(id=4)# Hits the Hits the database.c=p.hometown# Hits the database.

You can refer to any or relation in the list of fields passed to .

You can also refer to the reverse direction of a in the list of fields passed to — that is, you can traverse a back to the object on which the field is defined. Instead of specifying the field name, use the for the field on the related object.

There may be some situations where you wish to call with a lot of related objects, or where you don’t know all of the relations. In these cases it is possible to call with no arguments. This will follow all non-null foreign keys it can find - nullable foreign keys must be specified. This is not recommended in most cases as it is likely to make the underlying query more complex, and return more data, than is actually needed.

If you need to clear the list of related fields added by past calls of on a , you can pass as a parameter:

>>> without_relations=queryset.select_related(None)

Chaining calls works in a similar way to other methods - that is that is equivalent to .


Returns a that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to , in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

works by creating an SQL join and including the fields of the related object in the statement. For this reason, gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, is limited to single-valued relationships - foreign key and one-to-one.

, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using , in addition to the foreign key and one-to-one relationships that are supported by . It also supports prefetching of and , however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a is only supported if the query is restricted to one .

For example, suppose you have these models:

fromdjango.dbimportmodelsclassTopping(models.Model):name=models.CharField(max_length=30)classPizza(models.Model):name=models.CharField(max_length=50)toppings=models.ManyToManyField(Topping)def__str__(self):return"%s (%s)"%(,", ".join(topping.namefortoppinginself.toppings.all()),)

and run:

>>> Pizza.objects.all()["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...

The problem with this is that every time asks for it has to query the database, so will run a query on the Toppings table for every item in the Pizza .

We can reduce to just two queries using :

>>> Pizza.objects.all().prefetch_related('toppings')

This implies a for each ; now each time is called, instead of having to go to the database for the items, it will find them in a prefetched cache that was populated in a single query.

That is, all the relevant toppings will have been fetched in a single query, and used to make that have a pre-filled cache of the relevant results; these are then used in the calls.

The additional queries in are executed after the has begun to be evaluated and the primary query has been executed.

If you have an iterable of model instances, you can prefetch related attributes on those instances using the function.

Note that the result cache of the primary and all specified related objects will then be fully loaded into memory. This changes the typical behavior of , which normally try to avoid loading all objects into memory before they are needed, even after a query has been executed in the database.


Remember that, as always with , any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query. So, if you write the following:

>>> pizzas=Pizza.objects.prefetch_related('toppings')>>> [list(pizza.toppings.filter(spicy=True))forpizzainpizzas]

…then the fact that has been prefetched will not help you. The implied , but is a new and different query. The prefetched cache can’t help here; in fact it hurts performance, since you have done a database query that you haven’t used. So use this feature with caution!

Also, if you call the database-altering methods , , or , on , any prefetched cache for the relation will be cleared.

You can also use the normal join syntax to do related fields of related fields. Suppose we have an additional model to the example above:


The following are all legal:

>>> Restaurant.objects.prefetch_related('pizzas__toppings')

This will prefetch all pizzas belonging to restaurants, and all toppings belonging to those pizzas. This will result in a total of 3 database queries - one for the restaurants, one for the pizzas, and one for the toppings.

>>> Restaurant.objects.prefetch_related('best_pizza__toppings')

This will fetch the best pizza and all the toppings for the best pizza for each restaurant. This will be done in 3 database queries - one for the restaurants, one for the ‘best pizzas’, and one for the toppings.

The relationship could also be fetched using to reduce the query count to 2:

>>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')

Since the prefetch is executed after the main query (which includes the joins needed by ), it is able to detect that the objects have already been fetched, and it will skip fetching them again.

Chaining calls will accumulate the lookups that are prefetched. To clear any behavior, pass as a parameter:

>>> non_prefetched=qs.prefetch_related(None)

One difference to note when using is that objects created by a query can be shared between the different objects that they are related to i.e. a single Python model instance can appear at more than one point in the tree of objects that are returned. This will normally happen with foreign key relationships. Typically this behavior will not be a problem, and will in fact save both memory and CPU time.

While supports prefetching relationships, the number of queries will depend on the data. Since a can reference data in multiple tables, one query per table referenced is needed, rather than one query for all the items. There could be additional queries on the table if the relevant rows have not already been fetched.

in most cases will be implemented using an SQL query that uses the ‘IN’ operator. This means that for a large a large ‘IN’ clause could be generated, which, depending on the database, might have performance problems of its own when it comes to parsing or executing the SQL query. Always profile for your use case!

Note that if you use to run the query, calls will be ignored since these two optimizations do not make sense together.

You can use the object to further control the prefetch operation.

In its simplest form is equivalent to the traditional string based lookups:

>>> fromdjango.db.modelsimportPrefetch>>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))

You can provide a custom queryset with the optional argument. This can be used to change the default ordering of the queryset:

>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.order_by('name')))

Or to call when applicable to reduce the number of queries even further:

>>> Pizza.objects.prefetch_related(... Prefetch('restaurants',queryset=Restaurant.objects.select_related('best_pizza')))

You can also assign the prefetched result to a custom attribute with the optional argument. The result will be stored directly in a list.

This allows prefetching the same relation multiple times with a different ; for instance:

>>> vegetarian_pizzas=Pizza.objects.filter(vegetarian=True)>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas',to_attr='menu'),... Prefetch('pizzas',queryset=vegetarian_pizzas,to_attr='vegetarian_menu'))

Lookups created with custom can still be traversed as usual by other lookups:

>>> vegetarian_pizzas=Pizza.objects.filter(vegetarian=True)>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=vegetarian_pizzas,to_attr='vegetarian_menu'),... 'vegetarian_menu__toppings')

Using is recommended when filtering down the prefetch result as it is less ambiguous than storing a filtered result in the related manager’s cache:

>>> queryset=Pizza.objects.filter(vegetarian=True)>>>>>> # Recommended:>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=queryset,to_attr='vegetarian_pizzas'))>>> vegetarian_pizzas=restaurants[0].vegetarian_pizzas>>>>>> # Not recommended:>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=queryset))>>> vegetarian_pizzas=restaurants[0].pizzas.all()

Custom prefetching also works with single related relations like forward or . Generally you’ll want to use for these relations, but there are a number of cases where prefetching with a custom is useful:

  • You want to use a that performs further prefetching on related models.

  • You want to prefetch only a subset of the related objects.

  • You want to use performance optimization techniques like :

    >>> queryset=Pizza.objects.only('name')>>>>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('best_pizza',queryset=queryset))

When using multiple databases, will respect your choice of database. If the inner query does not specify a database, it will use the database selected by the outer query. All of the following are valid:

>>> # Both inner and outer queries will use the 'replica' database>>> Restaurant.objects.prefetch_related('pizzas__toppings').using('replica')>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings'),... ).using('replica')>>>>>> # Inner will use the 'replica' database; outer will use 'default' database>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.using('replica')),... )>>>>>> # Inner will use 'replica' database; outer will use 'cold-storage' database>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.using('replica')),... ).using('cold-storage')


The ordering of lookups matters.

Take the following examples:

>>> prefetch_related('pizzas__toppings','pizzas')

This works even though it’s unordered because already contains all the needed information, therefore the second argument is actually redundant.

>>> prefetch_related('pizzas__toppings',Prefetch('pizzas',queryset=Pizza.objects.all()))

This will raise a because of the attempt to redefine the queryset of a previously seen lookup. Note that an implicit queryset was created to traverse as part of the lookup.

>>> prefetch_related('pizza_list__toppings',Prefetch('pizzas',to_attr='pizza_list'))

This will trigger an because doesn’t exist yet when is being processed.

This consideration is not limited to the use of objects. Some advanced techniques may require that the lookups be performed in a specific order to avoid creating extra queries; therefore it’s recommended to always carefully order arguments.

(select=None, where=None, params=None, tables=None, order_by=None, select_params=None

Sometimes, the Django query syntax by itself can’t easily express a complex clause. For these edge cases, Django provides the modifier — a hook for injecting specific clauses into the SQL generated by a .

Use this method as a last resort

This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing . We are no longer improving or fixing bugs for this method.

For example, this use of :

>>> qs.extra(... select={'val':"select col from sometable where othercol = %s"},... select_params=(someparam,),... )

is equivalent to:

>>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s",(someparam,)))

The main benefit of using is that you can set if needed. The main downside is that if you refer to some table alias of the queryset in the raw SQL, then it is possible that Django might change that alias (for example, when the queryset is used as a subquery in yet another query).


You should be very careful whenever you use . Every time you use it, you should escape any parameters that the user can control by using in order to protect against SQL injection attacks.

You also must not quote placeholders in the SQL string. This example is vulnerable to SQL injection because of the quotes around :


You can read more about how Django’s SQL injection protection works.

By definition, these extra lookups may not be portable to different database engines (because you’re explicitly writing SQL code) and violate the DRY principle, so you should avoid them if possible.

Specify one or more of , , or . None of the arguments is required, but you should use at least one of them.

  • The argument lets you put extra fields in the clause. It should be a dictionary mapping attribute names to SQL clauses to use to calculate that attribute.


    Entry.objects.extra(select={'is_recent':"pub_date > '2006-01-01'"})

    As a result, each object will have an extra attribute, , a boolean representing whether the entry’s is greater than Jan. 1, 2006.

    Django inserts the given SQL snippet directly into the statement, so the resulting SQL of the above example would be something like:


    The next example is more advanced; it does a subquery to give each resulting object an attribute, an integer count of associated objects:

    Blog.objects.extra(select={'entry_count':'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id ='},)

    In this particular case, we’re exploiting the fact that the query will already contain the table in its clause.

    The resulting SQL of the above example would be:


    Note that the parentheses required by most database engines around subqueries are not required in Django’s clauses. Also note that some database backends, such as some MySQL versions, don’t support subqueries.

    In some rare cases, you might wish to pass parameters to the SQL fragments in . For this purpose, use the parameter.

    This will work, for example:


    If you need to use a literal inside your select string, use the sequence .

  • /

    You can define explicit SQL clauses — perhaps to perform non-explicit joins — by using . You can manually add tables to the SQL clause by using .

    and both take a list of strings. All parameters are “AND”ed to any other search criteria.


    Entry.objects.extra(where=["foo='a' OR bar = 'a'","baz = 'a'"])

    …translates (roughly) into the following SQL:


    Be careful when using the parameter if you’re specifying tables that are already used in the query. When you add extra tables via the parameter, Django assumes you want that table included an extra time, if it is already included. That creates a problem, since the table name will then be given an alias. If a table appears multiple times in an SQL statement, the second and subsequent occurrences must use aliases so the database can tell them apart. If you’re referring to the extra table you added in the extra parameter this is going to cause errors.

    Normally you’ll only be adding extra tables that don’t already appear in the query. However, if the case outlined above does occur, there are a few solutions. First, see if you can get by without including the extra table and use the one already in the query. If that isn’t possible, put your call at the front of the queryset construction so that your table is the first use of that table. Finally, if all else fails, look at the query produced and rewrite your addition to use the alias given to your extra table. The alias will be the same each time you construct the queryset in the same way, so you can rely upon the alias name to not change.

  • If you need to order the resulting queryset using some of the new fields or tables you have included via use the parameter to and pass in a sequence of strings. These strings should either be model fields (as in the normal method on querysets), of the form or an alias for a column that you specified in the parameter to .

    For example:

    q=Entry.objects.extra(select={'is_recent':"pub_date > '2006-01-01'"})q=q.extra(order_by=['-is_recent'])

    This would sort all the items for which is true to the front of the result set ( sorts before in a descending ordering).

    This shows, by the way, that you can make multiple calls to and it will behave as you expect (adding new constraints each time).

  • The parameter described above may use standard Python database string placeholders — to indicate parameters the database engine should automatically quote. The argument is a list of any extra parameters to be substituted.



    Always use instead of embedding values directly into because will ensure values are quoted correctly according to your particular backend. For example, quotes will be escaped correctly.






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 , and you query for , both rows will match. To prevent this, perform the correct typecasting before using the value in a query.


In some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.

This is done by passing the names of the fields to not load to :


A queryset that has deferred fields will still return model instances. Each deferred field will be retrieved from the database if you access that field (one at a time, not all the deferred fields at once).

You can make multiple calls to . Each call adds new fields to the deferred set:

# Defers both the body and headline fields.Entry.objects.defer("body").filter(rating=5).defer("headline")

The order in which fields are added to the deferred set does not matter. Calling with a field name that has already been deferred is harmless (the field will still be deferred).

You can defer loading of fields in related models (if the related models are loading via ) by using the standard double-underscore notation to separate related fields:


If you want to clear the set of deferred fields, pass as a parameter to :

# Load all fields immediately.my_queryset.defer(None)

Some fields in a model won’t be deferred, even if you ask for them. You can never defer the loading of the primary key. If you are using to retrieve related models, you shouldn’t defer the loading of the field that connects from the primary model to the related one, doing so will result in an error.


The method (and its cousin, , below) are only for advanced use-cases. They provide an optimization for when you have analyzed your queries closely and understand exactly what information you need and have measured that the difference between returning the fields you need and the full set of fields for the model will be significant.

Even if you think you are in the advanced use-case situation, only use defer() when you cannot, at queryset load time, determine if you will need the extra fields or not. If you are frequently loading and using a particular subset of your data, the best choice you can make is to normalize your models and put the non-loaded data into a separate model (and database table). If the columns must stay in the one table for some reason, create a model with (see the

  1. Restoration hardware dutch industrial
  2. Free ppt template
  3. Supersonic tab
  4. Battle net application
  5. Chidori effect

Advanced Models

In this chapter, we’ll dig much deeper into Django’s models and comprehensively explore the essentials.

In the first section of the chapter, we’ll explore the common data management functions built into Django. We’ll cover common model methods that return QuerySets (and those that don’t), model field lookups, aggregate functions, and building complex queries.

In later sections of the chapter, we’ll cover adding and overriding model managers and model methods, and have a look at how model inheritance works in Django.

Working With Data

Django’s QuerySet API provides a comprehensive array of methods and functions for working with data. In this section of the chapter, we will look at the common QuerySet methods, field lookups and aggregate functions, and how to build more complex queries with query expressions and objects.

Methods That Return QuerySets

Table 9.1 lists all the built-in model methods that return QuerySets.

Filter by the given lookup parameters. Multiple parameters are joined by SQL statements (See Chapter 4)
Filter by objects that don’t match the given lookup parameters
Annotate each object in the QuerySet. Annotations can be simple values, a field reference or an aggregate expression
Change the default ordering of the QuerySet
Reverse the default ordering of the QuerySet
Perform an SQL query to eliminate duplicate rows
Returns dictionaries instead of model instances
Returns tuples instead of model instances
Returns a QuerySet containing all available dates in the specified date range
Returns a QuerySet containing all available dates in the specified date and time range
Create an empty QuerySet
Return a copy of the current QuerySet
Use the SQL operator to combine two or more QuerySets
Use the SQL operator to return the shared elements of two or more QuerySets
Use the SQL operator to return elements in the first QuerySet that are not in the others
Select all related data when executing the query (except many-to-many relationships)
Select all related data when executing the query (including many-to-many relationships)
Do not retrieve the named fields from the database. Used to improve query performance on complex datasets
Opposite of —return only the named fields
Select which database the QuerySet will be evaluated against (when using multiple databases)
Return a QuerySet and lock table rows until the end of the transaction
Execute a raw SQL statement
Combine two QuerySets with the SQL operator. Using is functionally equivalent to using with multiple parameters
Combine two QuerySets with the SQL operator

Table 9-1: Model methods that return QuerySets.

Let’s use the Django interactive shell to explore a few examples of the more common QuerySet methods not already covered in the book.

Modify the Filters To Suit Your Data

The examples in this chapter use data from my database. You will need to modify filters and search parameters to suit the data in your database. Date formats are also specific to your locale, so you may have to swap day and month parameters.

The data returned in the examples are illustrative. If you’re paying attention, you will see that the answers come from different datasets. This is because I have worked on many versions of this chapter over time. As your data will be different anyway, I have not changed all the examples to reflect a single dataset.


will return a QuerySet of objects that don’t match the given lookup parameters, for example:

Using more than one lookup parameter will use an SQL operator under the hood:

The extra step in this example is because is a foreign key to the model, so we first have to retrieve a object.


Annotations can be simple values, a field reference or an aggregate expression. For example, let’s use Django’s aggregate function to annotate our model with a total of all users attending each event:

order_by() and reverse()

changes the default ordering of the QuerySet. Function parameters are the model fields to use to order the QuerySet. Ordering can be single level:

Or ordering can be multi-level. In the following example, the events are first ordered by event date and then by event name:

By default, QuerySet fields are ordered in ascending order. To sort in descending order, use the (minus) sign:

reverses the default ordering of the QuerySet:

A model must have default ordering (by setting the option of the models class) for to be useful. If the model is unordered, the sort order of the returned QuerySet will be meaningless.

Also, note both and are not free operations—they come at a time cost to your database and should be used sparingly on large datasets.

values() and values_list()

returns Python dictionaries, instead of a QuerySet object:

You can also specify which fields you want returned:

is the same as , except it returns tuples:

You can also specify which fields to return:

dates() and datetimes()

You use the and methods to return time-bounded records from the database (for example, all the events occurring in a particular month). For , these time bounds are , , and . adds , and bounds. Some examples:

select_related() and prefetch_related()

Selecting related information can be a database-intensive operation, as each foreign key relationship requires an additional database lookup. For example, each object in our database has a foreign key relationship with the table:

For our simple example, this is not a problem, but in large databases with many foreign key relationships, the load on the database can be prohibitive.

You use to improve database performance by retrieving all related data the first time the database is hit:

works the same way as , except it will work across many-to-many relationships.

Executing Raw SQL

While Django’s developers provide the query method for executing raw SQL, you are explicitly discouraged from doing so.

The Django ORM is very powerful. In the vast majority of cases where I have seen programmers resort to SQL it has been due to incomplete knowledge of Django’s ORM on the programmers part, not a deficiency in the ORM.

If you find yourself in the situation where a query is so complex you can’t find a way of completing the task with Django’s ORM, it’s likely you need to create a stored procedure or a new view within the database itself.

Methods That Don’t Return QuerySets

Table 9.2 lists all the built-in model methods that don’t return QuerySets.

Returns a single object. Throws an error if lookup returns multiple objects
Shortcut method to create and save an object in one step
Returns a single object. If the object doesn’t exist, it creates one
Updates a single object. If the object doesn’t exist, it creates one
Insert a list of objects in the database
Update given fields in the listed model instances
Count the number of objects in the returned QuerySet. Returns an integer
Return a QuerySet containing all objects with the listed IDs
Evaluate a QuerySet and return an iterator over the results. Can improve performance and memory use for queries that return a large number of objects
Return the latest object in the database table based on the given field(s)
Return the earliest object in the database table based on the given field(s)
Return the first object matched by the QuerySet
Return the last object matched by the QuerySet
Return a dictionary of aggregate values calculated over the QuerySet
Returns if the QuerySet contains any results
Performs an SQL on the specified field(s)
Performs an SQL that deletes all rows in the QuerySet
Return a class instance containing a copy of the QuerySet’s methods
Returns a string of the QuerySet’s execution plan. Used for analyzing query performance

Table 9-2: Model methods that don’t return QuerySets.

Let’s return to the Django interactive shell to dig deeper into some common examples not already covered in the book.


will attempt to retrieve a record matching the search fields. If a record doesn’t exist, it will create one. The return value will be a tuple containing the created or retrieved object and a boolean value that will be if a new record was created:

If we try to create the object a second time, it will retrieve the new record from the database instead.


works similar to , except you pass the search fields and a dictionary named containing the fields to update. If the object doesn’t exist, the method will create a new record in the database:

If the record exists, Django will update all fields listed in the dictionary:

bulk_create() and bulk_update()

The method saves time by inserting multiple objects into the database at once, most often in a single query. The function has one required parameter—a list of objects:

, on the other hand, takes a list of model objects and updates individual fields on selected model instances. For example, let’s say the first two “Smiths” in the database were entered incorrectly. First, we retrieve all the “Smiths”:

will only work on a list of objects, so first, we must create a list of objects we want to update:

Then, we make the modifications to the objects in the list:

We can then use the function to save the changes to the database in a single query:


Counts the number of objects in the QuerySet. Can be used to count all objects in a database table:

Or used to count the number of objects returned by a query:

is functionally equivalent to using the function, but has a cleaner syntax, and is likely to be faster on large datasets. For example:


takes a list of id values and returns a dictionary mapping each id to an instance of the object with that id. If you don’t pass a list , all objects will be returned:

Once retrieved, you can access each object by their key value:

Any non-empty list will retrieve all records with the listed ids:

List ids don’t have to be sequential either:

latest() and earliest()

Return the latest or the earliest date in the database for the provided field(s):

first() and last()

Returns the first or last object in the QuerySet:


Returns a dictionary of aggregate values calculated over the QuerySet. For example:

For a list of all aggregate functions available in Django, see Aggregate Functions later in this chapter.


Returns if the returned QuerySet contains one or more objects, if the QuerySet is empty. There are two common use-cases—to check if an object is contained in another QuerySet:

And to check if a query returns an object:

Field Lookups

Field lookups have a simple double-underscore syntax:

For example:

A complete list of Django’s field lookups is in Table 9-3.

Under the hood, Django creates SQL clauses to construct database queries from the applied lookups. Multiple lookups are allowed, and field lookups can also be chained (where logical):

/Exact match. is the case-insensitive version
/Field contains search text. is the case-insensitive version
In a given iterable (list, tuple or QuerySet)
/Greater than/greater than or equal
/Less than/less than or equal
/Starts with search string. is the case-insensitive version
/Ends with search string. is the case-insensitive version
Range test. Range includes start and finish values
Casts the value as a date. Used for datetime field lookups
Searches for an exact year match
Searches for an exact ISO 8601 year match
Searches for an exact month match
Searches for an exact day match
Searches for an exact week match
Searches for an exact day of the week match
Searches for an exact quarter of the year match. Valid integer range: 1–4
Casts the value as a time. Used for field lookups
Searches for an exact hour match
Searches for an exact minute match
Searches for an exact second match
Checks if field is null. Returns or
/Regular expression match. is the case-insensitive version

Table 9-3: Django’s model field lookups.

Aggregate Functions

Django includes seven aggregate functions:

  • . Returns the mean value of the expression.
  • . Counts the number of returned objects.
  • . Returns the maximum value of the expression.
  • . Returns the minimum value of the expression.
  • . Returns the population standard deviation of the data in the expression.
  • . Returns the sum of all values in the expression.
  • . Returns the population variance of the data in the expression.

They are translated to the equivalent SQL by Django’s ORM.

Aggregate functions can either be used directly:

Or with the function:

More Complex Queries

Query Expressions

Query expressions describe a computation or value used as a part of another query. There are six built-in query expressions:

  • . Represents the value of a model field or annotated column.
  • . Base type for database functions like and .
  • . All aggregate functions inherit from .
  • . Expression value. Not used directly.
  • . Used to wrap expressions of different types.
  • . Add a subquery to a QuerySet.

Django supports multiple arithmetic operators with query expressions, including:

  • Addition and subtraction
  • Multiplication and division
  • Negation
  • Modulo arithmetic; and
  • The power operator

We have already covered aggregation in this chapter, so let’s have a quick look at the other two commonly used query expressions: and .

F() Expressions

The two primary uses for expressions is to move computational arithmetic from Python to the database and to reference other fields in the model.

Let’s start with a simple example: say we want to delay the first event in the event calendar by two weeks. A conventional approach would look like this:

In this example, Django retrieves information from the database into memory, uses Python to perform the computation—in this case, add 14 days to the event date—and then saves the record back to the database.

For this example, the overhead for using Python to perform the date arithmetic is not excessive; however, for more complex queries, there is a definite advantage to moving the computational load to the database.

Now let’s see how we accomplish the same task with an expression:

We’re not reducing the amount of code we need to write here, but by using the expression, Django creates an SQL query to perform the computational logic inside the database rather than in memory with Python.

While this takes a huge load off the Django application when executing complex computations, there is one drawback—because the calculations take place inside the database, Django is now out of sync with the updated state of the database. We can test this by looking at the object instance:

To retrieve the updated object from the database, we need to use the function:

The second use for expressions—referencing other model fields—is straightforward. For example, you can check for users with the same first and last name:

This simple syntax works with all of Django’s field lookups and aggregate functions.

Func() Expressions

expressions can be used to represent any function supported by the underlying database (e.g. , , , , , etc.). For example:

Notice how we are using expressions again to reference another field in the model.

Q() Objects

Like expressions, a object encapsulates an SQL expression inside a Python object. objects are most often used to construct complex database queries by chaining together multiple expressions using () and () operators:

You can also perform queries using the negate () character:

Model Managers

A is a Django class that provides the interface between database query operations and a Django model. Each Django model is provided with a default named . We used the default manager in Chapter 4 and again in this chapter every time we query the database, for example:

In each example, is the default for the model instance.

You can customize the default class by extending the base class for the model. The two most common use-cases for customizing the default manager are:

  1. Adding extra manager methods; and
  2. Modifying initial QuerySet results.

Extra manager methods add table-level functionality to models. To add row-level functions, i.e., methods that act on single instances of the model, you use model methods, which we cover in the next section of the chapter.

Extra manager methods are created by inheriting the base class and adding custom functions to the custom class. For example, let’s create an extra manager method for the model to retrieve the total number of events for a particular event type (changes in bold):

Let’s have a look at this partial listing from your app’s file:

  • In line 1, we’ve entered a new class called that inherits from Django’s base class.
  • Lines 2 and 3 define the custom manager method we’re adding to the model. This new method returns the total number of the specified event type. Note we’re using the field lookup to return all events that have the key phrase in the title.
  • In line 13 we’re replacing the default manager with our new class. Note that inherits from the base class, so all the default manager methods like and are included in the custom class.

Once it has been created, you can use your new manager method just like any other model method:

The Shell and Changing Model Code

Any changes made to models are not applied unless you restart the shell, so this applies not only to this example but any other examples that modify model code.

Renaming the Default Model Manager

While the base manager for each model is named by default, you can change the name of the default manager in your class declaration. For example, to change the default manager name for our class from “objects” to “events”, we just need to change line 13 in the code above from:


Now you can refer to the default manager like so:

Overriding Initial Manager QuerySets

To change what is returned by the default manager QuerySet, you override the method. This is easiest to understand with an example. Let’s say we regularly have to check what venues are listed in our local city. To cut down on the number of queries we have to write, we will create a custom manager for our model (changes in bold):

Let’s look at the changes:

  • Lines 5 to 7 define the new class. The structure is the same as the class, except this time we’re overriding the default method and returning a filtered list that only contains local venues. This assumes local venues have a “00000” zip code. In a real website, you would have a valid zip code here, or better still, a value for the local zip code saved in your settings file.
  • In line 18 we’ve renamed the default manager to .
  • In line 19 we’re adding the custom model manager ().

Note there is no limit to how many custom managers you can add to a Django model instance. This makes creating custom filters for common queries a breeze. Once you have saved the file, you can use the custom methods in your code. For example, the default manager method has been renamed, so you can use the more intuitive , instead of :

And our new custom manager is also easily accessible:

Model Methods

Django’s class comes with many built-in methods. We have already used some of them—, , and others. Where manager methods add table-level functionality to Django’s models, model methods add row-level functions that act on individual instances of the model.

There are two common cases where you want to play with model methods:

  1. When you want to add business logic to the model by adding custom model methods; and
  2. When you want to override the default behavior of a built-in model method.

Custom Model Methods

As always, it’s far easier to understand how custom model methods work by writing a couple, so let’s modify our class (changes in bold):

Let’s have a look at what’s happening with this new code:

  • In line 10 I have added a new method called . This is a straightforward method that compares the event date to the date passed to the method. It returns a message stating whether the event occurs before, on or after the date.
  • In line 19 I have added another custom method that returns a slugified event name. The decorator on line 18 allows us to access the method directly, like an attribute. Without the , you would have to use a method call ().

Let’s test these new methods out in the Django interactive interpreter. Don’t forget to save the model before you start!

First, the method:

This should be easy to follow. Notice how the decorator allows us to access the method directly like it was an attribute. I.e., instead of .

Now, to test the method (assuming you have an event named “Gala Day”):

Too easy.

Date and Time in Django

Remember, Django uses timezone aware dates, so if you are making date comparisons like this in any of your code, not just in class methods, you can’t use without timezone information as Django will throw a . To avoid this error, you must provide timezone information with your dates.

Overriding Default Model Methods

It’s common to want to override built-in model methods like and to add business logic to default database behavior.

To override a built-in model method, you define a new method with the same name. For example, let’s override the model’s default method to assign management of the event to a staff member (changes in bold):

The new method starts on line 10. In the overridden method, we’re first assigning the staff member with the username “admin” to the field of the model instance (line 11). This code assumes you have named your admin user ‘admin’. If not, you will have to change this code.

Then we call the default method with the function to save the model instance to the database (line 12).

Once you save your file, you can test out the overridden model method in the Django interactive shell (Remember, the username you entered on line 11 has to exist in the database for the test to work):

Once the new record is created, you can test to see if your override worked by checking the field of the object:

Model Inheritance

Don’t Build Custom User Models Like This!

The following examples are a convenient way to show you how multi-table inheritance and abstract base classes work without messing up the models in your database.

This is not how you would go about creating a custom user model as it’s not connected to Django’s authentication system. Also, Django’s class includes , , and fields, so you need not create them yourself.

I will show you how to extend Django’s class in Chapter 14.

Models are Python classes, so inheritance works the same way as normal Python class inheritance. The two most common forms of model inheritance in Django are:

  1. Multi-table inheritance, where each model has its own database table; and
  2. Abstract base classes, where the parent model holds information common to all its child classes but doesn’t have a database table.

You can also create proxy models to modify the Python-level behavior of a model without modifying the underlying model fields, however, we won’t be covering them here. See the Django documentation for more information on proxy models.

Multi-table Inheritance

With multi-table inheritance, the parent class is a normal model, and the child inherits the parent by declaring the parent class in the child class declaration. For example:

The parent model in the example is the model from our app. The model inherits from and adds an additional field (). As they are both standard Django model classes, a database table is created for each model. I’ve created these models in my database, so you can see the tables Django creates (Figure 9-1).

Figure 9-1: Database tables are created for both the parent and the child model. You will only see these tables if you run the example code.

Abstract Base Classes

Abstract base classes are handy when you want to put common information into other models without having to create a database table for the base class.

You create an abstract base class by adding the class option (line 7 in this illustrative example):

Abstract base classes are also useful for declaring class options that are inherited by all child models (line 8).

As the model from our app now inherits the first name, last name and email fields from , it only needs to declare the function to behave the same way as the original model we created earlier.

This example is very similar to the example for multi-table inheritance in the previous section, and if you saved and migrated these models, you would get the same result as Figure 9-1—Django would create the and tables in your database, but, because is an abstract model, it won’t be added to the database as a table.

Chapter Summary

In this chapter, we dug much deeper into Django’s models, exploring the essentials of Django’s models.

We looked at the common data management functions built into Django. We also learned about the common model methods that return QuerySets and those that don’t, model field lookups, aggregate functions, and building complex queries.

We also covered adding and overriding model managers and model methods, and had a look at how model inheritance works in Django.

In the next chapter, we will take a similar deep-dive into the inner workings of Django’s views.

What is the future of Django / Is Django becoming obsolete?

6. How to select some fields only in a queryset?¶


The model has a number of fields in it. But sometimes, you do not need to use all the fields. In such situations, we can query only desired fields.

Django provides two ways to do this

  • values and values_list methods on queryset.
  • only_method

Say, we want to get and of all the users whose name starts with R. You do not want the fetch the other fields to reduce the work the DB has to do.

>>> queryset=User.objects.filter( first_name__startswith='R').values('first_name', 'last_name')>>> queryset<QuerySet [{'first_name': 'Ricky', 'last_name': 'Dayal'}, {'first_name': 'Ritesh', 'last_name': 'Deshmukh'}, {'first_name': 'Radha', 'last_name': 'George'}, {'first_name': 'Raghu', 'last_name': 'Khan'}, {'first_name': 'Rishabh', 'last_name': 'Deol'}]

You can verify the generated sql using , which gives.


The output will be list of dictionaries.

Alternatively, you can do

>>> queryset=User.objects.filter( first_name__startswith='R').only("first_name", "last_name")

, gives us


The only difference between and is also fetches the .


Only django


Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.

— Apple Developer Documentation

Together with authentication and throttling, permissions determine whether a request should be granted or denied access.

Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the and properties to determine if the incoming request should be permitted.

Permissions are used to grant or deny access for different classes of users to different parts of the API.

The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the class in REST framework.

A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the class in REST framework.

How permissions are determined

Permissions in REST framework are always defined as a list of permission classes.

Before running the main body of the view each permission in the list is checked. If any permission check fails an or exception will be raised, and the main body of the view will not run.

When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:

  • The request was successfully authenticated, but permission was denied. — An HTTP 403 Forbidden response will be returned.
  • The request was not successfully authenticated, and the highest priority authentication class does not use headers. — An HTTP 403 Forbidden response will be returned.
  • The request was not successfully authenticated, and the highest priority authentication class does use headers. — An HTTP 401 Unauthorized response, with an appropriate header will be returned.

Object level permissions

REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.

Object level permissions are run by REST framework's generic views when is called. As with view level permissions, an exception will be raised if the user is not allowed to act on the given object.

If you're writing your own views and want to enforce object level permissions, or if you override the method on a generic view, then you'll need to explicitly call the method on the view at the point at which you've retrieved the object.

This will either raise a or exception, or simply return if the view has the appropriate permissions.

For example:

Note: With the exception of , the provided permission classes in do not implement the methods necessary to check object permissions.

If you wish to use the provided permission classes in order to check object permissions, you must subclass them and implement the method described in the Custom permissions section (below).

Limitations of object level permissions

For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.

Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.

Because the method is not called, object level permissions from the method are not applied when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the method of your ViewSet class.

Setting the permission policy

The default permission policy may be set globally, using the setting. For example.

If not specified, this setting defaults to allowing unrestricted access:

You can also set the authentication policy on a per-view, or per-viewset basis, using the class-based views.

Or, if you're using the decorator with function based views.

Note: when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the file.

Provided they inherit from , permissions can be composed using standard Python bitwise operators. For example, could be written:

Note: it supports & (and), | (or) and ~ (not).


The permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.

This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.


The permission class will deny permission to any unauthenticated user, and allow permission otherwise.

This permission is suitable if you want your API to only be accessible to registered users.


The permission class will deny permission to any user, unless is in which case permission will be allowed.

This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.


The will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; , or .

This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.


This permission class ties into Django's standard model permissions. This permission must only be applied to views that have a property or method. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.

  • requests require the user to have the permission on the model.
  • and requests require the user to have the permission on the model.
  • requests require the user to have the permission on the model.

The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a model permission for requests.

To use custom model permissions, override and set the property. Refer to the source code for details.


Similar to , but also allows unauthenticated users to have read-only access to the API.


This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian.

As with , this permission must only be applied to views that have a property or method. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned.

  • requests require the user to have the permission on the model instance.
  • and requests require the user to have the permission on the model instance.
  • requests require the user to have the permission on the model instance.

Note that does not require the package, and should support other object-level backends equally well.

As with you can use custom model permissions by overriding and setting the property. Refer to the source code for details.

Note: If you need object level permissions for , and requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the class provided by the package. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.

To implement a custom permission, override and implement either, or both, of the following methods:

    The methods should return if the request should be granted access, and otherwise.

    If you need to test if a request is a read operation or a write operation, you should check the request method against the constant , which is a tuple containing , and . For example:

    Note: The instance-level method will only be called if the view-level checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call . If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising on failure.)

    Custom permissions will raise a exception if the test fails. To change the error message associated with the exception, implement a attribute directly on your custom permission. Otherwise the attribute from will be used. Similarly, to change the code identifier associated with the exception, implement a attribute directly on your custom permission - otherwise the attribute from will be used.


    The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.

    As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:

    Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling from the view once you have the object instance. This call will raise an appropriate if any object-level permission checks fail, and will otherwise simply return.

    Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.

    REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.

    • /: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The method can apply different querysets based on the current action.
    • /: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)
    • /: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The method can apply different serializers based on the current action.

    The following table lists the access restriction methods and the level of control they offer over which actions.

    Action: listglobalnoobject-level*
    Action: createnoglobalobject-level
    Action: retrieveglobalobject-levelobject-level
    Action: updateglobalobject-levelobject-level
    Action: partial_updateglobalobject-levelobject-level
    Action: destroyglobalobject-levelno
    Can reference action in decisionno**yesno**
    Can reference request in decisionno**yesyes

    * A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned.
    ** The methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.

    The following third party packages are also available.

    DRF - Access Policy

    The Django REST - Access Policy package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.

    Composed Permissions

    The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.

    REST Condition

    The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.

    DRY Rest Permissions

    The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.

    Django Rest Framework Roles

    The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.

    Django REST Framework API Key

    The Django REST Framework API Key package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. machines) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.

    Django Rest Framework Role Filters

    The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.

    Django Rest Framework PSQ

    The Django Rest Framework PSQ package is an extension that gives support for having action-based permission_classes, serializer_class, and queryset dependent on permission-based rules.

    Why you should use Django for data science

    Katya's fists clenched, her knuckles turned white, but the girl endured. - Relax your ass, it will be easier, - I whispered to her and she seems to have heard me and tried to relax and the phallus began to gradually. Enter her anus.

    You will also like:

    To cough up. I took out a member, took the eggs in my hands and let her lick them, then again a member, then again eggs. I was catching an unearthly high.

    4325 4326 4327 4328 4329