0
0
Djangoframework~30 mins

Why ORM maps Python to database in Django - See It in Action

Choose your learning style9 modes available
Why ORM Maps Python to Database
📖 Scenario: Imagine you are building a simple app to keep track of books in a library. You want to save book details like title and author in a database, but you want to work with Python code instead of writing raw database commands.
🎯 Goal: You will create a Django model to represent books, configure a simple setting, write a query to get books, and complete the setup to see how Python code connects to the database using ORM.
📋 What You'll Learn
Create a Django model class called Book with fields title and author
Add a configuration variable MAX_BOOKS set to 100
Write a query using Django ORM to get all books with titles longer than 5 characters
Complete the model with a __str__ method to return the book title
💡 Why This Matters
🌍 Real World
ORM lets developers work with databases using Python code instead of SQL. This makes apps easier to build and maintain.
💼 Career
Understanding ORM is key for backend developers working with Django or similar frameworks to handle data storage efficiently.
Progress0 / 4 steps
1
Create the Book model
Create a Django model class called Book with two fields: title as a CharField with max length 100, and author as a CharField with max length 50.
Django
Need a hint?

Use models.CharField for text fields and set max_length as instructed.

2
Add a configuration variable
Add a variable called MAX_BOOKS and set it to 100 below the model class.
Django
Need a hint?

Just create a variable with the exact name and value.

3
Write a Django ORM query
Write a Django ORM query called long_title_books that gets all Book objects with title longer than 5 characters. Import Length from django.db.models.functions and use annotate(title_length=Length('title')) with filter(title_length__gt=5).
Django
Need a hint?

Import Length from django.db.models.functions and use Book.objects.annotate(title_length=Length('title')).filter(title_length__gt=5).

4
Add the __str__ method
Add a __str__ method inside the Book model class that returns the title of the book.
Django
Need a hint?

The __str__ method helps show the book title when you print or view the object.