0
0
Djangoframework~20 mins

Ordering and slicing querysets in Django - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Queryset Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this queryset slicing?
Given a Django model Book with 10 entries ordered by published_date, what does Book.objects.order_by('published_date')[2:5] return?
AA queryset with the 2nd, 3rd, and 4th books ordered by published_date
BA queryset with the last 3 books ordered by published_date
CA queryset with the 3rd, 4th, and 5th books ordered by published_date
DA queryset with the 1st, 2nd, and 3rd books ordered by published_date
Attempts:
2 left
💡 Hint
Remember Python slicing starts at index 0 and excludes the stop index.
📝 Syntax
intermediate
2:00remaining
Which queryset ordering syntax is correct?
Select the correct way to order a queryset of Author by last name descending and then first name ascending.
AAuthor.objects.order_by('last_name', '-first_name')
BAuthor.objects.order_by('-last_name', 'first_name')
CAuthor.objects.order_by('last_name-', 'first_name')
DAuthor.objects.order_by('last_name desc', 'first_name asc')
Attempts:
2 left
💡 Hint
Use a minus sign before the field name for descending order.
🔧 Debug
advanced
2:00remaining
Why does this queryset slicing cause an error?
Consider this code: books = Book.objects.order_by('title')[5:2]. What happens when this runs?
AReturns an empty queryset because the slice start is greater than stop
BRaises a SyntaxError due to invalid slice syntax
CReturns the last 3 books ordered by title
DRaises a ValueError because slicing with start > stop is not allowed
Attempts:
2 left
💡 Hint
Think about how Python slicing behaves when start index is larger than stop index.
🧠 Conceptual
advanced
2:00remaining
How does chaining order_by calls affect the queryset?
What is the result of this queryset: Book.objects.order_by('author').order_by('published_date')?
AThe queryset is ordered only by published_date, ignoring author
BThe queryset is ordered by author and published_date combined
CThe queryset is ordered first by author, then by published_date
DRaises an error because multiple order_by calls are not allowed
Attempts:
2 left
💡 Hint
Each order_by call overrides the previous ordering.
state_output
expert
2:00remaining
What is the number of items in this sliced queryset?
If Entry.objects.all() returns 15 items, how many items does Entry.objects.order_by('-created_at')[3:10] contain?
A12 items
B6 items
C10 items
D7 items
Attempts:
2 left
💡 Hint
Count the items between indices 3 and 9 inclusive.