Course Content
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Class Meta
In Django, the Meta
class is a special class within a model that provides metadata about the model. It's used to configure aspects like database table names, ordering, verbose names, and much more. Understanding Meta options is crucial for effectively customizing and optimizing your Django models.
Common Meta Options
- db_table: specifies the database table name;
- ordering: determines the default ordering of records;
- verbose_name: define human-readable singular name for the model;
- verbose_name_plural: define human-readable plural name for the model;
- unique_together: sets a tuple of fields that must be unique when considered together;
- index_together: similar to unique_together, but for indexes;
- permissions: custom permissions for the model;
- get_latest_by: Field name to use in the latest() method.
Practical Examples
In the Book
model, unique_together
ensures that no two books have the same title and author. get_latest_by
makes it easy to retrieve the most recently published book.
Note
To indicate descending order, use an optional
-
prefix: ordering=["-publication_date"].
Thanks for your feedback!