0
0
Djangoframework~20 mins

all() and filter() methods in Django - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Django Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
1:30remaining
What does Model.objects.all() return?
In Django, when you call Model.objects.all(), what type of object do you get back?
AA list of dictionaries representing each record.
BA QuerySet containing all records of the Model in the database.
CA single Model instance representing the first record.
DAn integer count of all records in the Model.
Attempts:
2 left
💡 Hint
Think about what Django returns to let you work with multiple records easily.
component_behavior
intermediate
1:30remaining
What does Model.objects.filter(field=value) return?
In Django, what does Model.objects.filter(field=value) return?
AA QuerySet with all records where <code>field</code> equals <code>value</code>.
BA single Model instance where <code>field</code> equals <code>value</code>.
CA boolean indicating if any record matches <code>field=value</code>.
DA list of primary keys of matching records.
Attempts:
2 left
💡 Hint
Remember, filter narrows down records but still returns multiple if found.
state_output
advanced
2:00remaining
What is the output of this Django QuerySet code?
Given the following Django model and code, what is the output of print(qs.count())?
Django
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)

# Assume database has 3 products: 
# Product(name='Pen', price=1.50), Product(name='Book', price=10.00), Product(name='Notebook', price=5.00)

qs = Product.objects.filter(price__gt=5.00)
print(qs.count())
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Look at which products have price greater than 5.00.
📝 Syntax
advanced
1:30remaining
Which option causes a syntax error in Django QuerySet filtering?
Which of the following Django QuerySet filter calls will cause a syntax error?
AModel.objects.filter(active=True)
BModel.objects.filter(price__gte=10, price__lte=20)
CModel.objects.filter('name'='test')
DModel.objects.filter(name__icontains='test')
Attempts:
2 left
💡 Hint
Check how keyword arguments are passed in Python functions.
🔧 Debug
expert
2:30remaining
Why does this Django QuerySet filter return no results?
Given this code, why does qs return an empty QuerySet?
Django
qs = Product.objects.filter(name__startswith='Pen', price__lt=1.00)
AThe <code>startswith</code> lookup is case-sensitive and no product matches.
BThe filter syntax is incorrect and causes a runtime error.
CThe database connection is lost, so no results are returned.
DNo products have a name starting with 'Pen' and price less than 1.00 at the same time.
Attempts:
2 left
💡 Hint
Think about the conditions combined with AND logic in filter.