Recall & Review
beginner
What does the
order_by() method do in a Django queryset?The
order_by() method sorts the queryset results based on one or more model fields. You can specify ascending order by field name or descending order by prefixing the field name with a minus sign (-).Click to reveal answer
beginner
How do you get the first 5 records from a Django queryset?
You use slicing syntax like
queryset[:5]. This limits the queryset to the first 5 records, similar to how you slice a list in Python.Click to reveal answer
intermediate
What happens if you chain
order_by() multiple times on a queryset?Only the last
order_by() call takes effect. It overrides any previous ordering specified in earlier calls.Click to reveal answer
intermediate
Explain how negative slicing works on Django querysets.
Negative slicing like
queryset[:-3] is not supported in Django querysets and will raise an error. You can only slice with positive start and stop indexes.Click to reveal answer
intermediate
How can you order a queryset by multiple fields?
Pass multiple field names to
order_by() separated by commas, like order_by('field1', '-field2'). The queryset is ordered by the first field, then by the second field as a tiebreaker.Click to reveal answer
What does
MyModel.objects.all().order_by('-created_at') do?✗ Incorrect
The minus sign (-) before 'created_at' means descending order.
Which of these is the correct way to get the first 10 records from a queryset?
✗ Incorrect
Slicing with [:10] returns the first 10 records.
What happens if you call
order_by('name').order_by('age') on a queryset?✗ Incorrect
The last order_by call overrides the previous one.
Is negative slicing like
queryset[:-5] allowed in Django querysets?✗ Incorrect
Negative slicing is not supported and causes an error.
How do you order a queryset by 'last_name' ascending and then 'first_name' descending?
✗ Incorrect
Pass multiple fields with '-' prefix for descending order.
Describe how to order a Django queryset by multiple fields and then slice it to get a subset of results.
Think about chaining order_by and slicing like list operations.
You got /4 concepts.
Explain why negative slicing is not supported on Django querysets and how you can work around it.
Consider how querysets translate to database queries.
You got /4 concepts.