Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 77 ยท Models and the ORM

Custom Managers, QuerySets and Model Methods

Put query logic where it belongs in Django - write custom managers and chainable QuerySets, add model methods and properties, and enforce rules with Meta constraints.

As a project grows, the same filters appear in view after view: "published books", "orders from the last 30 days", "users who confirmed their email". Copying filter(status="published") everywhere is a recipe for bugs, because the day the rule changes you must find every copy. Django gives you a place for such rules: the model layer. A well-designed model knows how to query itself and how to protect its own data.

This lesson covers four tools. Managers and custom QuerySets hold reusable queries. Model methods and properties hold behavior that belongs to a single row. Meta options such as ordering and constraints describe rules that the database enforces. You should know models and basic queries before you start.

Each example installs Django in your browser and uses an in-memory SQLite database. The code before the model definitions is the same setup block as in the other ORM lessons.

What a manager is

Every model that does not define one gets a manager called objects. A manager is the gateway for queries on the table: Book.objects.filter(...), Book.objects.create(...). Internally, a manager builds a QuerySet from its get_queryset() method, and all the familiar methods (filter, exclude, order_by, ...) are forwarded to it.

flowchart LR
    M["Book.objects<br/>(Manager)"] -->|"get_queryset()"| Q["QuerySet"]
    Q -->|".filter() / .exclude()"| Q2["new QuerySet"]
    Q2 -->|"iterate, count, get..."| DB[("database")]

A manager creates the first queryset; each method returns a new queryset until you evaluate it.

You can add your own managers in two ways, and which one you choose decides how reusable your queries are.

Option 1: change the starting point with get_queryset()

Subclass models.Manager and override get_queryset() to narrow the default rows. The manager below only ever sees published books.

Python A manager that returns only published books

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few rules for this style:

  • Keep a plain manager first. The first manager defined on a model becomes its _default_manager, which Django uses for things such as dumpdata, related-object access and the admin. If that manager hides rows, you get surprising "not found" errors. That is why objects = models.Manager() comes before published.
  • A filtering manager is hard to bypass by accident, but it cannot be chained with other custom methods (Book.published.cheaper_than(10) does not exist).
  • Related lookups such as author.books.all() use the default manager's behavior for the related model, so a filtering default manager can hide related rows. This is the main reason to leave the first manager unfiltered.

Option 2: a chainable QuerySet

The more flexible approach is to write the reusable filters on a QuerySet subclass and attach it with as_manager(). Because the methods live on the queryset, they chain in any order, and each call returns another BookQuerySet:

Python
objects = BookQuerySet.as_manager()

If you also need manager-only methods, Manager.from_queryset(BookQuerySet) builds a manager class that copies the queryset's public methods, and you can subclass it. For the common case, as_manager() is enough. The same example shows model methods and properties, which come next.

Python Chainable queryset methods and model behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because every step returns a queryset, Book.objects.published().since(2018).cheaper_than(13) stays lazy: Django builds one SQL statement and runs it only when you iterate. Name queryset methods after business ideas (published, overdue, for_user) rather than after SQL, and your views read like sentences.

Model methods and properties

Anything about one row belongs on the model class:

  • A method performs an action or takes arguments: book.publish(), order.apply_coupon(code).
  • A @property computes a value that reads like a field: book.price_with_tax. It is not stored in the database, so you cannot filter on it. For filtering, use an annotation or a GeneratedField (see Raw SQL and Database Features).
  • __str__() makes objects readable in the shell, in logs and in the admin.
  • get_absolute_url() returns the canonical URL of an object, using reverse(). The admin and templates use it for "view on site" links.

The habit of putting this behavior on the model is called the fat model, thin view approach: views translate HTTP into method calls, and the rules live in one testable place. The publish example above keeps its rule (you cannot publish twice) in publish(), so the admin, a form and an API view all behave the same way.

Tip: "Fat models" can go too far. When a model class grows to hundreds of lines or a rule involves several models and external services, move that logic into a plain function or a service module and call it from the model or view. Keep on the model what is about this row.

Be careful when you override save() to add behavior. Calls such as bulk_create(), QuerySet.update() and delete() on a queryset do not run save(), so rules that must always hold belong in constraints (below) rather than in save() alone. When you only change some columns, save(update_fields=[...]) writes just those and avoids overwriting other fields changed by someone else.

Meta options: ordering and constraints

The inner class Meta configures the table rather than a row.

ordering = ["-edition", "title"] sets the default order of every query on the model. It is convenient, and it is also a cost: the database sorts every result, even when you do not care. Many teams skip Meta.ordering on big tables and order explicitly in the queries that need it.

Constraints are rules the database enforces, so they hold no matter which code path writes the data, including raw SQL and scripts. Django offers two classes:

  • CheckConstraint(condition=Q(...), name=...) says that a condition must be true for every row, such as a price that is never negative.
  • UniqueConstraint(fields=[...], name=...) makes a combination of fields unique. Add condition=Q(...) for a partial unique rule that applies only to some rows, for example "titles must be unique among published books".

Constraints need a unique name. Add them to the model and create a migration so the database gets the new rules. (The parameter was called check before Django 5.1; use condition in new code.)

Python Ordering and constraints in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a write breaks a constraint the database raises IntegrityError, and Django passes it on. For friendly messages, call instance.full_clean() or instance.validate_constraints(); model forms and the admin already do this and show the problem next to the form instead of crashing. The database remains the last line of defense, which matters when two requests race each other. The next lesson, Transactions and Concurrency, shows how to deal with that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should objects = models.Manager() usually be defined before a filtering manager such as published?

    Django uses the first manager as _default_manager. If it hides rows, related-object access and other tools may behave in surprising ways.
  2. 2. What is the main advantage of QuerySet.as_manager() over overriding get_queryset() in a manager?

    Methods defined on the QuerySet return querysets, so Book.objects.published().since(2018).cheaper_than(13) works and stays lazy.
  3. 3. A rule says a price must never be negative, even for data written by scripts that bypass your model code. Where should the rule live?

    A CheckConstraint is enforced by the database for every write. save() is skipped by bulk_create() and queryset update().
  4. 4. What does UniqueConstraint(fields=['title'], condition=Q(status='published'), name='...') allow?

    The condition makes it a partial unique constraint: only rows matching the condition take part in the uniqueness check.

Summary

  • A manager is a model's entry point for queries; it builds querysets with get_queryset().
  • Override get_queryset() to change the default rows, and keep an unfiltered objects manager first.
  • Put reusable filters on a QuerySet subclass and expose them with as_manager() (or Manager.from_queryset()) so they chain.
  • Model methods and properties hold behavior of one row; keep views thin, but move multi-model workflows into services.
  • Meta.ordering sets a default sort at a cost; CheckConstraint(condition=...) and UniqueConstraint (optionally with condition) enforce rules in the database.
  • save() is not called by bulk operations, so important rules belong in constraints.

Next: Transactions and Concurrency.