Challenge - 5 Problems
ORM Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Why use ORM in Django?
What is the main reason Django's ORM maps Python classes to database tables?
Attempts:
2 left
💡 Hint
Think about how ORM helps developers avoid writing raw SQL.
✗ Incorrect
Django's ORM lets developers use Python classes and objects to interact with the database. This means you write Python code instead of SQL queries, making database work easier and less error-prone.
❓ component_behavior
intermediate2:00remaining
What happens when you save a Django model instance?
Given a Django model instance, what does calling the .save() method do in terms of ORM behavior?
Django
class Book(models.Model): title = models.CharField(max_length=100) book = Book(title='Learn Django') book.save()
Attempts:
2 left
💡 Hint
Think about how ORM syncs Python objects with the database.
✗ Incorrect
Calling .save() on a Django model instance tells the ORM to write the data to the database. If the object is new, it inserts a new row; if it exists, it updates the row.
📝 Syntax
advanced2:00remaining
Identify the correct Django ORM query syntax
Which option correctly retrieves all Book objects with title 'Django Basics' using Django ORM?
Attempts:
2 left
💡 Hint
Remember the Django ORM uses 'objects' manager and 'filter' method for queries.
✗ Incorrect
The correct way to query multiple objects matching a condition is using Book.objects.filter(). Other options are invalid methods or missing the manager.
🔧 Debug
advanced2:00remaining
Why does this Django ORM query raise an error?
What error will this code raise and why?
class Author(models.Model):
name = models.CharField(max_length=50)
# Query:
Author.objects.get(name='Unknown')
Attempts:
2 left
💡 Hint
What happens if get() finds no matching record?
✗ Incorrect
The get() method expects exactly one matching record. If none exist, Django raises a DoesNotExist error.
❓ state_output
expert2:00remaining
What is the output of this Django ORM code snippet?
Consider this code:
class Product(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=5, decimal_places=2)
Product.objects.create(name='Pen', price=1.50)
Product.objects.create(name='Notebook', price=3.00)
cheap_products = Product.objects.filter(price__lt=2.00)
print(list(cheap_products.values_list('name', flat=True)))
What will be printed?
Attempts:
2 left
💡 Hint
Look at the filter condition price__lt=2.00 and which products match.
✗ Incorrect
The filter price__lt=2.00 selects products with price less than 2.00. Only 'Pen' has price 1.50, so the output is ['Pen'].