skip to content

Model Classes

How a Django model maps to a table: field classes and options, relations and on_delete rules, Meta constraints, inheritance styles and custom fields. Interviewers test schema design in the ORM.

part ofDjangooverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

In Django, why does a GenericForeignKey get no database foreign-key constraint, and when would you replace it with concrete ForeignKeys?

level: seniorimportance: should knowfreq 42%

basics

~20 s

object_id can hold a key from any table, so the database cannot declare a constraint on it; integrity, cascades and joins move into Django. For a few fixed targets, nullable ForeignKeys with a CheckConstraint, or per-target tables, restore both.

open as a page

When should a Django model use a UUIDField primary key instead of BigAutoField, and what does that choice cost in storage and index performance?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Use a UUID key when ids must be unguessable or created outside the database. It costs a wider key in every index and foreign key, char(32) off PostgreSQL and MariaDB, and random uuid4 values scatter inserts across the index; time-ordered UUIDv7 avoids that.

open as a page

A Django fleet app stores Car and Van as multi-table children of Vehicle, and bulk imports, deletes and row locks misbehave; which write costs does multi-table inheritance add?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Each child save writes one row per level inside a transaction, bulk_create() raises ValueError for multi-table children, bulk_update() adds a query per ancestor, deleting a child also deletes its parent row unless keep_parents=True, and select_for_update(of=...) must name the parent link.

open as a page

In Django 6.1, when is a model instance in memory stale, and when do you still need refresh_from_db()?

level: seniorimportance: should knowfreq 38%

basics

~20 s

An instance holds the values read when it was loaded; QuerySet.update(), other processes and raw SQL change the row without touching it. refresh_from_db() reloads its fields. Since Django 6.0, F() assignments are refreshed automatically on save().

open as a page

In a Django model, when do you declare Meta.indexes with Index(condition=...), include= or expressions instead of setting db_index=True on a field?

level: seniorimportance: should knowfreq 32%

basics

~10 s

db_index=True gives one plain single-column index. Meta.indexes with models.Index adds multi-column, descending, partial (condition), covering (include) and functional (expressions) indexes. Those need a name, and some backends ignore condition or include.

open as a page

In Django, how does on_delete=RESTRICT differ from on_delete=PROTECT, and when does RESTRICT still let a delete go through?

level: seniorimportance: should knowfreq 33%

basics

~10 s

PROTECT refuses any delete that reaches a protected row. RESTRICT refuses it too, except when the restricted rows are themselves being deleted through a CASCADE path in the same operation; then the delete proceeds.

open as a page

In Django, is on_delete=CASCADE enforced by Python or by the database, and what changes when you switch to Django 6.1's DB_CASCADE?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Classic CASCADE runs in Python: Django's deletion collector finds the related rows and deletes them itself, sending delete signals. Django 6.1's DB_CASCADE writes ON DELETE CASCADE into the foreign key instead, so the database deletes children without Django fetching them or sending signals.

open as a page

In Django's JSONField, how do SQL NULL and JSON null differ, and why must its default be a callable like dict?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

Assigning None to a JSONField stores SQL NULL; a JSON null needs Django 6.1's JSONNull() expression, and both read back as None. Its default must be a callable such as dict, or all instances share one mutable object.

open as a page

In Django 5.2+, how do you key a line-item table by (order, line_no) with CompositePrimaryKey, and what are its current limits?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

Declare pk = models.CompositePrimaryKey('order_id', 'line_no'); pk becomes a tuple usable in filters. Limits: ForeignKey and generic relations cannot target the model, the admin cannot register it, and Django cannot migrate a table to or from it.

open as a page

In Django, which Meta options does a child model inherit from an abstract base class, and which from a multi-table parent?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

A child of an abstract base inherits the whole Meta if it declares none, with abstract reset to False, and can extend it by subclassing Base.Meta; a multi-table or proxy child inherits only ordering and get_latest_by.

open as a page

In Django, a feed shows 50 likes and reads like.content_object for each; how do prefetch_related and GenericPrefetch cut the query count?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Each content_object read runs its own query. prefetch_related('content_object') groups likes by content type and runs one query per target model; GenericPrefetch, new in Django 5.0, supplies a custom queryset per type, such as one using select_related or only().

open as a page

With Django's register_lookup(), how would you let queries filter a custom MoneyField by currency, as in total__currency='EUR', and why use a Transform?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Write a Transform subclass with lookup_name = 'currency', an SQL template extracting the code and output_field = CharField(), then register it with MoneyField.register_lookup(). A Transform yields a value, so exact, in and order_by chain after it.

open as a page

showing 31–42 of 42