0
0
Djangoframework~15 mins

String representation with __str__ in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
String representation with __str__ in Django models
📖 Scenario: You are building a simple Django app to manage a library's book collection. Each book has a title and an author.When you view the list of books in the Django admin or in the Django shell, you want to see a friendly name for each book instead of the default object representation.
🎯 Goal: Create a Django model called Book with fields for title and author. Then add a __str__ method to return a readable string like "Title by Author".
📋 What You'll Learn
Create a Django model named Book with title and author fields
Add a __str__ method to the Book model
The __str__ method should return a string formatted as "{title} by {author}"
Use exact variable and method names as specified
💡 Why This Matters
🌍 Real World
Customizing the string representation of models helps developers and admins quickly identify records in Django admin and shell.
💼 Career
Knowing how to add __str__ methods is a basic skill for Django developers to improve code readability and user experience.
Progress0 / 4 steps
1
Create the Book model with title and author fields
Create a Django model class called Book with two fields: title and author, both as models.CharField with max_length=100.
Django
Need a hint?

Use class Book(models.Model): to define the model. Use models.CharField(max_length=100) for both fields.

2
Add a __str__ method to the Book model
Add a method called __str__ inside the Book model class that returns a string. For now, return the title field only.
Django
Need a hint?

Define def __str__(self): and return self.title.

3
Update __str__ to include author in the string
Modify the __str__ method to return a string formatted as "{title} by {author}" using an f-string.
Django
Need a hint?

Use an f-string: return f"{self.title} by {self.author}".

4
Complete the model with proper indentation and imports
Ensure the entire Book model code includes the import statement, class definition, fields, and the __str__ method exactly as shown.
Django
Need a hint?

Check that all parts are present and properly indented.