0
0
Djangoframework~20 mins

Q objects for complex queries in Django - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Q Objects Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Django query return?
Given the Django model Book with fields title and published_year, what does this query return?

Book.objects.filter(Q(title__icontains='python') | Q(published_year__gte=2020))
ABooks with titles containing 'python' and published in or after 2020
BBooks published before 2020 or titles not containing 'python'
CBooks published before 2020 and titles containing 'python'
DBooks with titles containing 'python' or published in or after 2020
Attempts:
2 left
💡 Hint
Remember that the | operator means OR in Q objects.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Q object query
Which option shows the syntax error in combining Q objects to filter Author model by name and age?
Django
Author.objects.filter(Q(name='Alice') & Q(age__gt=30))
AQ(name='Alice') and Q(age__gt=30)
B)03=tg__ega(Q & )'ecilA'=eman(Q
CQ(name='Alice') & Q(age__gt=30)
DQ(name='Alice') | Q(age__gt=30)
Attempts:
2 left
💡 Hint
Check the operator used between Q objects.
state_output
advanced
2:00remaining
What is the count of results from this query?
Assuming the Product model has 10 items with category='electronics' and 5 items with price__lt=100, what is the count of Product.objects.filter(Q(category='electronics') & Q(price__lt=100))?
A5
BCannot determine without more info
C15
D10
Attempts:
2 left
💡 Hint
Think about how many products satisfy both conditions together.
🔧 Debug
advanced
2:00remaining
Why does this Q object query raise an error?
Consider this query:
Entry.objects.filter(Q(pub_date__year=2023) | 'title__icontains=django')
Why does it raise an error?
ABecause the second part is a string, not a Q object
BBecause Q objects cannot use | operator
CBecause pub_date__year is invalid lookup
DBecause filter() cannot accept Q objects
Attempts:
2 left
💡 Hint
Check the types combined with the | operator.
🧠 Conceptual
expert
3:00remaining
How to exclude objects matching multiple conditions using Q objects?
Which query excludes Customer objects whose status is 'inactive' or last_login is before 2022-01-01?
ACustomer.objects.exclude(Q(status='inactive') & Q(last_login__lt='2022-01-01'))
BCustomer.objects.filter(~Q(status='inactive') & ~Q(last_login__lt='2022-01-01'))
CCustomer.objects.exclude(Q(status='inactive') | Q(last_login__lt='2022-01-01'))
DCustomer.objects.filter(Q(status!='inactive') | Q(last_login__gte='2022-01-01'))
Attempts:
2 left
💡 Hint
Use exclude() with OR inside Q to remove any matching either condition.