Django Django Models & ORM 3 — Questions and Answers
Question 1: What does the `unique=True` argument on a model field enforce?
- That no two rows can have the same value for that field (Correct answer)
- That the field cannot be NULL
- That the field is indexed for faster lookup
- That the field is the primary key
Correct answer: That no two rows can have the same value for that field
Setting unique=True creates a UNIQUE constraint in the database, ensuring no two model instances share the same field value.
Question 2: Which abstract base class makes a model function as an abstract base, not creating its own database table?
- Setting abstract = True in Meta (Correct answer)
- Inheriting from AbstractModel
- Using @abstract decorator
- Setting db_table = None in Meta
Correct answer: Setting abstract = True in Meta
Setting abstract = True in the model's Meta class tells Django not to create a database table for that model; subclasses get their own tables with inherited fields.
Question 3: What does the `null=True` argument on a Django model field do?
- Allows the field to store NULL in the database (Correct answer)
- Makes the field optional in forms
- Sets the default value to None in Python
- Skips validation for this field
Correct answer: Allows the field to store NULL in the database
null=True allows the database column to store a NULL value; for string-based fields, Django convention prefers blank=True with an empty string instead.
Question 4: Which Django ORM method deletes all objects matching a QuerySet?
- QuerySet.delete() (Correct answer)
- QuerySet.remove()
- QuerySet.destroy()
- QuerySet.drop()
Correct answer: QuerySet.delete()
Calling delete() on a QuerySet removes all matching objects from the database in an efficient bulk DELETE SQL statement.
Question 5: What is a Django migration squash used for?
- Combining multiple migrations into a single migration file to reduce history (Correct answer)
- Rolling back all migrations at once
- Creating a fresh initial migration
- Syncing migrations between two databases
Correct answer: Combining multiple migrations into a single migration file to reduce history
Squashing migrations uses python manage.py squashmigrations to merge a range of migrations into one, speeding up fresh database setups.
Question 6: Which field option sets the default value for a Django model field?
- default= (Correct answer)
- initial=
- value=
- fallback=
Correct answer: default=
The default= argument provides a value used when no value is supplied for the field, which can be a constant or a callable.
What does the `unique=True` argument on a model field enforce?