← Back to Django, page 3

django-0055 · Easy fresher

What does the Meta class do in a Django model, and why define __str__()?

Meta holds model-level options that are not fields: default ordering, database table name, verbose names, constraints, indexes, unique_together-style rules and abstract inheritance settings. __str__() returns the human-readable label used by the admin, the shell, forms' select boxes and logs, so without it you see 'Student object (1)'.

Full answer
python
class Student(models.Model):
    name = models.CharField(max_length=40)
    joined = models.DateField()

    class Meta:
        ordering = ["name"]
        verbose_name_plural = "students"
        indexes = [models.Index(fields=["joined"])]
        constraints = [models.UniqueConstraint(fields=["name", "joined"], name="uniq_name_joined")]

    def __str__(self):
        return self.name

Common Meta options:

  • ordering: default ORDER BY for every query. It adds sorting cost to each query, so for big tables only set it when most reads need it. order_by() with no arguments clears it.
  • verbose_name and verbose_name_plural: names shown in the admin.
  • db_table: override the table name, which defaults to <app_label>_<model>.
  • indexes, constraints: database-level rules. Prefer constraints over the older unique_together.
  • abstract = True: the model is a template for children and gets no table.
  • app_label: needed for models defined outside an installed app.
  • get_latest_by: used by latest() and earliest().
  • permissions, default_related_name, managed = False (Django does not create or change the table, used for legacy tables or views).

__str__ is displayed in the admin list, in dropdowns for ForeignKey fields, and in print(obj). Keep it short, avoid queries inside it (it runs for every row of a list and creates N+1 problems when it touches a relation), and return a string.

Changing ordering or verbose_name produces an AlterModelOptions migration with no SQL, while changing db_table renames the table.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection


class Student(models.Model):
    name = models.CharField(max_length=40)
    joined = models.DateField()

    class Meta:
        app_label = "school"
        ordering = ["name"]
        verbose_name_plural = "students"
        constraints = [models.UniqueConstraint(fields=["name", "joined"], name="uniq_name_joined")]

    def __str__(self):
        return self.name


class Plain(models.Model):
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)

import datetime
for n in ("Ravi", "Asha", "Kiran"):
    Student.objects.create(name=n, joined=datetime.date(2026, 1, 5))

print(list(Student.objects.all()))                         # uses __str__ and Meta.ordering
print(str(Student.objects.all().query)[-40:])
print(str(Student.objects.order_by().query)[-30:])         # order_by() clears default ordering
print(str(Plain()))                                        # no __str__ defined
print(Student._meta.verbose_name_plural, Student._meta.db_table)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): [<Student: Asha>, <Student: Kiran>, <Student: Ravi>] nt" ORDER BY "school_student"."name" ASC "joined" FROM "school_student" Plain object (None) students school_student

Key points

  • Meta carries ordering, indexes, constraints, table names and abstract settings
  • __str__ gives readable labels in admin, shell and forms
  • Default ordering adds ORDER BY to every query
  • Avoid relation lookups inside __str__ (N+1)
  • Prefer constraints over unique_together

Common mistakes

  • Skipping __str__ and getting 'Student object (1)' everywhere
  • Setting default ordering on a huge table that rarely needs it
  • Using unique_together in new code
  • Running queries inside __str__

Follow-ups

  • How do you make a field-level ordering that does not affect every query?
  • What does managed = False do?
  • How do abstract base classes use Meta?

Tips

  • List 5 Meta options
  • Warn about default ordering cost
  • Mention __str__ in admin