In Chapter 4, we presented an introduction to Django’s database layer – how to define models and how to use the database API to create, retrieve, update and delete records. In this chapter, we’ll introduce you to some more advanced features of this part of Django.
Recall our book models from Chapter 4:
As we explained in Chapter 4, accessing the value for a particular field on a database object is as straightforward as using an attribute. For example, to determine the title of the book with ID 50, we’d do the following:
But one thing we didn’t mention previously is that related objects – fields expressed as either a
ManyToManyField – act slightly differently.
When you access a field that’s a
ForeignKey, you’ll get the related model object. For example:
ForeignKey fields, it works the other way, too, but it’s slightly different due to the non-symmetrical nature of the relationship. To get a list of books for a given publisher, use
publisher.book_set.all(), like this:
Behind the scenes,
book_set is just a
QuerySet (as covered in Chapter 4), and it can be filtered and sliced like any other
QuerySet. For example:
The attribute name
book_set is generated by appending the lower case model name to
Many-to-many values work like foreign-key values, except we deal with
QuerySet values instead of model instances. For example, here’s how to view the authors for a book:
It works in reverse, too. To view all of the books for an author, use
author.book_set, like this:
Here, as with
ForeignKey fields, the attribute name
book_set is generated by appending the lower case model name to
In the statement
objects is a special attribute through which you query your database. In Chapter 4, we briefly identified this as the model’s manager. Now it’s time to dive a bit deeper into what managers are and how you can use them.
In short, a model’s manager is an object through which Django models perform database queries. Each Django model has at least one manager, and you can create custom managers in order to customize database access. There are two reasons you might want to create a custom manager: to add extra manager methods, and/or to modify the initial
QuerySet the manager returns.
Adding extra manager methods is the preferred way to add table-level functionality to your models. (For row-level functionality – i.e., functions that act on a single instance of a model object – use model methods, which are explained later in this chapter.)
For example, let’s give our
Book model a manager method
title_count() that takes a keyword and returns the number of books that have a title containing that keyword. (This example is slightly contrived, but it demonstrates how managers work.)
BookManagerclass that extends
django.db.models.Manager. This has a single method,
title_count(), which does the calculation. Note that the method uses
selfrefers to the manager itself.
objectsattribute on the model. This has the effect of replacing the “default” manager for the model, which is called
objectsand is automatically created if you don’t specify a custom manager. We call it
objectsrather than something else, so as to be consistent with automatically created managers.
With this manager in place, we can now do this:
Obviously, this is just an example – if you typed this in at your interactive prompt, you will likely get different return values.
Why would we want to add a method such as
title_count()? To encapsulate commonly executed queries so that we don’t have to duplicate code.
A manager’s base
QuerySet returns all objects in the system. For example,
Book.objects.all() returns all books in the book database. You can override a manager’s base
QuerySet by overriding the
get_queryset() should return a
QuerySet with the properties you require.
For example, the following model has two managers – one that returns all objects, and one that returns only the books by Roald Dahl.
With this sample model,
Book.objects.all() will return all books in the database, but
Book.dahl_objects.all() will only return the ones written by Roald Dahl. Note that we explicitly set
objects to a vanilla
Manager instance, because if we hadn’t, the only available manager would be
dahl_objects. Of course, because
get_queryset() returns a
QuerySet object, you can use
exclude() and all the other
QuerySet methods on it. So these statements are all legal:
This example also pointed out another interesting technique: using multiple managers on the same model. You can attach as many
Manager() instances to a model as you’d like. This is an easy way to define common “filters” for your models. For example:
This example allows you to request
Person.people.all(), yielding predictable results. If you use custom
Manager objects, take note that the first
Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets this first
Manager defined in a class as the “default”
Manager, and several parts of Django (though not the admin application) will use that
Manager exclusively for that model.
As a result, it’s often a good idea to be careful in your choice of default manager, in order to avoid a situation where overriding of
get_queryset() results in an inability to retrieve objects you’d like to work with.
Define custom methods on a model to add custom row-level functionality to your objects. Whereas managers are intended to do table-wide things, model methods should act on a particular model instance. This is a valuable technique for keeping business logic in one place – the model.
An example is the easiest way to explain this. Here’s a model with a few custom methods:
The model instance reference in Appendix A has a complete list of methods automatically given to each model. You can override most of these (see below) but there are a couple that you’ll almost always want to define:
__str__(). A Python “magic method” that returns a Unicode “representation” of any object. This is what Python and Django will use whenever a model instance needs to be coerced and displayed as a plain string. Most notably, this happens when you display an object in an interactive console or in the admin.You’ll always want to define this method; the default isn’t very helpful at all.
get_absolute_url(). This tells Django how to calculate the URL for an object. Django uses this in its admin interface, and any time it needs to figure out a URL for an object. Any object that has a URL that uniquely identifies it should define this method.
There’s another set of model methods that encapsulate a bunch of database behavior that you’ll want to customize. In particular, you’ll often want to change the way
delete() work. You’re free to override these methods (and any other model method) to alter behavior. A classic use-case for overriding the built-in methods is if you want something to happen whenever you save an object. For example, (see
save() for documentation of the parameters it accepts):
You can also prevent saving:
It’s important to remember to call the superclass method – that’s that
super(Blog, self).save(*args, **kwargs) business – to ensure that the object still gets saved into the database. If you forget to call the superclass method, the default behavior won’t happen and the database won’t get touched.
It’s also important that you pass through the arguments that can be passed to the model method – that’s what the
*args, **kwargs bit does. Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments. If you use
*args, **kwargs in your method definitions, you are guaranteed that your code will automatically support those arguments when they are added.