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 pageshowhide
explore
- Column Types & Options6 questions
- Relations & Delete Rules6 questions
- Meta Options & Constraints5 questions
- Instance Methods & Saving5 questions
- Table Inheritance Styles6 questions
- Custom Column Types5 questions
- Generated Columns & Keys4 questions
- Content Types & Generic Relations5 questions
questions
page 2 of 2In Django, why does a GenericForeignKey get no database foreign-key constraint, and when would you replace it with concrete ForeignKeys?
basics
~20 sobject_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.
When should a Django model use a UUIDField primary key instead of BigAutoField, and what does that choice cost in storage and index performance?
basics
~20 sUse 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.
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?
basics
~20 sEach 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.
In Django 6.1, when is a model instance in memory stale, and when do you still need refresh_from_db()?
basics
~20 sAn 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().
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?
basics
~10 sdb_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.
In Django, how does on_delete=RESTRICT differ from on_delete=PROTECT, and when does RESTRICT still let a delete go through?
basics
~10 sPROTECT 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.
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?
basics
~20 sClassic 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.
In Django's JSONField, how do SQL NULL and JSON null differ, and why must its default be a callable like dict?
basics
~20 sAssigning 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.
In Django 5.2+, how do you key a line-item table by (order, line_no) with CompositePrimaryKey, and what are its current limits?
basics
~20 sDeclare 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.
In Django, which Meta options does a child model inherit from an abstract base class, and which from a multi-table parent?
basics
~20 sA 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.
In Django, a feed shows 50 likes and reads like.content_object for each; how do prefetch_related and GenericPrefetch cut the query count?
basics
~20 sEach 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().
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?
basics
~20 sWrite 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.
showing 31–42 of 42