Django Django Models & ORM 1 — Questions and Answers
Question 1: Which Django ORM method retrieves a single object and raises an exception if not found?
- get() (Correct answer)
- filter()
- first()
- fetch()
Correct answer: get()
The get() method returns a single object matching the query and raises DoesNotExist if no match or MultipleObjectsReturned if more than one match.
Question 2: What does the `on_delete=models.CASCADE` argument do in a ForeignKey field?
- Deletes related objects when the referenced object is deleted (Correct answer)
- Prevents deletion of the referenced object
- Sets the field to NULL on deletion
- Raises an error on deletion
Correct answer: Deletes related objects when the referenced object is deleted
CASCADE causes Django to automatically delete all objects that have a ForeignKey pointing to the deleted object.
Question 3: Which field type would you use to store a many-to-many relationship in a Django model?
- ManyToManyField (Correct answer)
- ForeignKey
- OneToOneField
- RelatedField
Correct answer: ManyToManyField
ManyToManyField creates a junction table in the database to store many-to-many relationships between two models.
Question 4: What is the purpose of Django's `Meta` class inside a model?
- To define model-level options like ordering and table name (Correct answer)
- To store model instance data
- To define model methods only
- To register the model with the admin
Correct answer: To define model-level options like ordering and table name
The inner Meta class allows you to set model-level metadata such as ordering, verbose_name, db_table, and unique_together constraints.
Question 5: Which ORM method returns a QuerySet of all objects matching a condition without raising exceptions?
- filter() (Correct answer)
- get()
- fetch()
- search()
Correct answer: filter()
filter() returns a QuerySet containing all objects that match the given lookup parameters, returning an empty QuerySet if none are found.
Question 6: What does the `__str__` method on a Django model do?
- Returns a human-readable string representation of the model instance (Correct answer)
- Converts the model to JSON
- Saves the model to the database
- Validates model fields
Correct answer: Returns a human-readable string representation of the model instance
Defining __str__ on a model controls how an instance is displayed as a string, which is used in the Django admin and shell.
Which Django ORM method retrieves a single object and raises an exception if not found?