print(result)?from django.db import models from django.db.models import Count class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) # Query result = Author.objects.annotate(num_books=Count('books')).values('name', 'num_books')
The annotate method adds a new field num_books to each Author, counting how many related Book objects they have. Authors with no books get 0.
Book model with a rating field, which Django ORM query correctly annotates each author with the average rating of their books?from django.db.models import Avg # Choose the correct query:
To annotate authors with the average rating of their related books, you use Avg('books__rating'). Option A misses the relation, C uses aggregate which returns a single value, and D has a typo in the related field name.
Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
It returns authors with 1 book instead of more than 1. Why?When annotating with Count on ManyToMany fields, duplicates can inflate counts. Adding distinct=True fixes this.
aggregate() and annotate() in Django ORM?aggregate() returns a dictionary with overall summary values for the whole queryset. annotate() adds calculated fields to each item in the queryset.
class Store(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
store = models.ForeignKey(Store, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
# Data:
# Store A has products priced 10.00, 20.00
# Store B has products priced 15.00
# Query:
from django.db.models import Max, F
result = Store.objects.annotate(
max_price=Max('product__price'),
discount_price=F('max_price') * 0.9
).values('name', 'max_price', 'discount_price').order_by('name')from django.db.models import Max, F result = Store.objects.annotate( max_price=Max('product__price'), discount_price=F('max_price') * 0.9 ).values('name', 'max_price', 'discount_price').order_by('name')
The max_price is the highest product price per store. The discount_price multiplies that by 0.9 using an F expression, which Django supports with numeric literals.