A query manager is a model-facing interface for working with database data. Every Django model gets the default manager, .objects, attached to its class. Use it to create model instances and begin queries without writing database statements directly. section 4.4 section 4.12
Call manager methods with keyword arguments that name model fields. For example, .create() inserts a row and returns the matching model object. Required fields must be supplied; missing values can fail only when Django executes the database statement. section 4.4
(venv) RiffMates$ python manage.py shell Python 3.12.1 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from bands.models import Musician >>> from datetime import date >>> steve = Musician.objects.create(first_name="Steve", last_name="Vai", birth=date(1960, 6, 6)) #1
Create a Musician through Musician.objects.create(), passing Python values for each model field. section 4.4
Methods such as .all() and .filter() return a QuerySet: a wrapper around a query, not necessarily its results yet. QuerySets are lazy, so Django can refine a query before fetching data; printing it, converting it to a list, or indexing it triggers evaluation. Use .first() when only the first result is needed rather than fetching everything first. section 4.4.1 section 4.12
Common starting points include:
- .all() builds a query for every object of the model. section 4.4.1
- .filter(first_name="John") builds a query for matching field values; lookups such as first_name__startswith="J" request comparisons instead of exact matches. section 4.12
- .get(last_name="Lennon") retrieves a matching object for use elsewhere, such as creating a relationship. section 4.7.2
Related fields also expose query managers. A Venue reached from Room.venue has a reverse .room_set manager that queries only rooms linked by that foreign key. A many-to-many field supplies a manager named for the field, such as Band.musicians, which can add related objects and query them; the other side receives band_set by default. section 4.7.1 section 4.7.2
Following relationships
After creating a Venue named CBGB and Room objects named Red and Blue with that venue, cbgb.room_set.all() returns its rooms. After adding Lennon through beatles.musicians.add(lennon), beatles.musicians.all() returns the associated musician. section 4.7.1 section 4.7.2
