The Django ORM lets Python classes represent database tables, turning stored records into objects that views can query and render through templates. It gives a multipage site a practical path from database content to web pages, whether the records are blog posts, merchandise, or user accounts. section 1.2 section 4.0
A typical ORM workflow looks like this:
- Define a model by inheriting from django.db.models.Model; fields describe stored data and provide access to queried values. section 4.12
- Run makemigrations to describe model changes in Python, then migrate to apply those changes to the database. section 4.12
- Use the model's .objects manager to retrieve records with .all(), .first(), .last(), and .filter(). section 4.12
- Change an instance with attribute assignment followed by .save(), or remove it with .delete(); the Python proxy remains after deletion. section 4.12
- Connect related records through one-to-many or many-to-many relationships, then consider the resulting tables and query cost. section 4.12 section 4.10
Filtering and displaying records
A view can ask for every record, select an exact value with .filter(first_name="John"), or find partial matches with .filter(first_name__startswith="J"). It can retrieve one object with get_object_or_404(), pass the result to a template, and use Paginator to divide query results into pages. section 4.12 section 1.2
The ORM is an abstraction, not permission to forget the database. Designing models as purely object-oriented Python structures can produce duplicated fields or inefficient SQL. A flatter table design may be better, and many-to-many relationships can require several lookups as related objects are assembled. section 4.10
Anything built with the ORM can also be managed through Django Admin, providing a web interface for database records such as user accounts. section 1.1.4
