from django.db.models import Count, Avg, Q
result = Book.objects.filter(
Q(author__country='India') | Q(published_year__gte=2020)
).annotate(
review_count=Count('reviews'),
avg_rating=Avg('reviews__rating')
).filter(
review_count__gte=5,
avg_rating__gte=4.0
).values('title', 'author__name').order_by('-avg_rating')Complex Query with Multiple Aggregations and Filtering
The query will fail because you cannot filter on annotated fields using filter()
The query finds books by Indian authors or published after 2020, with at least 5 reviews and average rating >= 4.0, returning title and author name sorted by rating
The Q object with OR operator will cause the entire filter to be ignored
The annotate() method cannot be used together with values() in the same query
Show answer & explanationAnswer
Correct answer
The query finds books by Indian authors or published after 2020, with at least 5 reviews and average rating >= 4.0, returning title and author name sorted by rating
Explanation
This query demonstrates Q objects for complex filtering, annotate() for aggregations, filtering on aggregated fields, and values() for selecting specific fields. The database executes a complex JOIN with GROUP BY and HAVING clauses.
All 40 Django ORM Queries and QuerySets questions
- 1.What is a QuerySet in Django ORM?
- 2.Which method is used to retrieve all objects from a model?
- 3.What does the `filter()` method return in Django ORM?
- 4.What is the difference between `filter()` and `get()` methods?
- 5.What does the `exclude()` method do in Django ORM?
- 6.How do you order QuerySet results in Django?
- 7.What does `count()` method return?
- 8.What is QuerySet slicing used for?
- 9.What does `exists()` method do?
- 10.What does the `distinct()` method do?
- 11.Understanding Django QuerySet Evaluation
- 12.Filtering Related Objects with select_related()
- 13.Scenario:
- 14.Understanding F() Objects in Django ORM
- 15.Aggregation with Django ORM
- 16.Scenario:
- 17.Understanding Prefetch_related() for Reverse Relations
- 18.Query Chaining and Method Order
- 19.Using values() vs values_list()
- 20.Scenario:
- 21.Understanding QuerySet Lazy Evaluation and Database Queries
- 22.Scenario:
- 23.Analyzing N+1 Query Problem in Django ORM
- 24.QuerySet Method Chaining and Filter Behavior
- 25.Scenario:
- 26.Understanding QuerySet Slicing and Caching Behavior
- 27.Aggregation and Annotation in Django ORM
- 28.Scenario:
- 29.Understanding F Objects and Database-Level Operations
- 30.Scenario:
- 31.Complex Query with Multiple Aggregations and Filtering
- 32.Scenario:
- 33.Understanding Subqueries and Exists()
- 34.Raw SQL Queries and Security
- 35.Case-Insensitive Lookups and Performance
- 36.Scenario:
- 37.Understanding Query Caching and Database Hits
- 38.Bulk Operations:
- 39.Scenario:
- 40.Understanding Query Optimization with explain()
