Bird
0
0

Which is the best way to implement get_queryset?

hard📝 Application Q15 of 15
Django - DRF Advanced Features
You want to implement a Django ListView that allows users to search products by name and order results by price or rating. You also want to prevent invalid ordering fields from causing errors. Which is the best way to implement get_queryset?
AFilter by search term, then order only if order param is in allowed list ['price', 'rating']
BFilter by search term, order by any order param without validation
COrder first by order param, then filter by search term
DIgnore search and order, just return all products
Step-by-Step Solution
Solution:
  1. Step 1: Understand the need for validation of ordering fields

    Allowing only specific fields prevents errors and security issues.
  2. Step 2: Apply filtering before ordering and validate order param

    Filter products by search term, then order only if order param is in ['price', 'rating'].
  3. Final Answer:

    Filter by search term, then order only if order param is in allowed list ['price', 'rating'] -> Option A
  4. Quick Check:

    Validate order param before ordering = Filter by search term, then order only if order param is in allowed list ['price', 'rating'] [OK]
Quick Trick: Validate order fields before ordering queryset [OK]
Common Mistakes:
MISTAKES
  • Ordering without checking allowed fields
  • Ordering before filtering
  • Ignoring search parameter completely

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes