0
0
Djangoframework~30 mins

Primary key behavior in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Primary key behavior
📖 Scenario: You are building a simple Django app to manage a list of books in a library. Each book needs a unique identifier so you can find it easily.
🎯 Goal: Create a Django model called Book with a primary key field and a title field. Understand how Django automatically creates a primary key if you don't specify one, and how to define your own primary key.
📋 What You'll Learn
Create a Django model named Book with a title field
Understand Django's default primary key behavior
Add a custom primary key field named isbn as a CharField
Use the primary_key=True attribute on the isbn field
💡 Why This Matters
🌍 Real World
Managing unique identifiers for records in a database is essential in real-world apps like libraries, stores, or user management.
💼 Career
Understanding primary keys is fundamental for backend developers working with databases and Django models.
Progress0 / 4 steps
1
Create the Book model with a title field
Create a Django model class called Book with a title field of type CharField with max length 100.
Django
Need a hint?

Use class Book(models.Model): and add title = models.CharField(max_length=100) inside.

2
Add a custom primary key field named isbn
Add a field called isbn to the Book model as a CharField with max length 13 and set primary_key=True.
Django
Need a hint?

Define isbn = models.CharField(max_length=13, primary_key=True) inside the Book class.

3
Explain Django default primary key behavior
Add a comment above the Book class explaining that Django automatically adds an id field as primary key if none is specified.
Django
Need a hint?

Write a comment starting with # Django automatically adds an 'id' field above the class.

4
Add __str__ method to display book title
Add a __str__ method to the Book model that returns the title field.
Django
Need a hint?

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