Recall & Review
beginner
What is the purpose of the
__str__ method in a Django model?The
__str__ method defines a human-readable string representation of the model instance. It helps display meaningful text instead of generic object info in the admin site and other places.Click to reveal answer
beginner
How do you define the
__str__ method inside a Django model?Inside your model class, define a method named
__str__(self) that returns a string describing the instance, usually using one or more fields of the model.Click to reveal answer
beginner
Example: What will this
__str__ method return?<br>def __str__(self):
return self.titleIt returns the value of the
title field of the model instance as its string representation.Click to reveal answer
intermediate
Why is it helpful to implement
__str__ in Django models?It makes the admin interface and debugging easier by showing clear, readable names for objects instead of default memory addresses or generic text.
Click to reveal answer
beginner
What happens if you don't define
__str__ in a Django model?Django will show a default string like
<ModelName object (id)>, which is less informative and harder to understand at a glance.Click to reveal answer
What should the
__str__ method in a Django model return?✗ Incorrect
The
__str__ method must return a string that clearly describes the model instance.Where is the
__str__ method commonly used in Django?✗ Incorrect
The
__str__ method helps show readable names in the admin site and when printing objects in the shell.What happens if you print a Django model instance without a
__str__ method?✗ Incorrect
Without
__str__, Django shows a generic string with the model name and id.Which of these is a good practice for
__str__ in a model representing books?✗ Incorrect
Returning the book's title gives a clear and useful description of the instance.
Can
__str__ return a formatted string using multiple fields?✗ Incorrect
__str__ can return any string, including formatted strings combining multiple fields.Explain why defining the
__str__ method in a Django model improves usability.Think about how you see model instances in the admin or shell.
You got /4 concepts.
Write a simple
__str__ method for a Django model with fields first_name and last_name.Combine the two fields to show full name.
You got /3 concepts.