Filtering related fields in django annotate () function

The Django documentation provides examples for using annotate () to create generalized results based on related QuerySet fields (i.e. using joins in annotate ()).

A simplified example from documents is, for example, Store.objects.annotate(min_price=Min('books__price'))where books are the ManyToMany field in the Book to Book, and price is the book field.

To continue this example, how do I create an annotated QuerySet of Store object with the lowest prices, not for all books in the store, but only for books with "author = 'William Shakespeare"? In other words, how do I filter the related fields used to compute the population?

+3
source share
1

, :

Store.objects.filter(books__author='William Shakespeare').annotate(
                     min_price=Min('books__price'))

, - , , .

+2

Source: https://habr.com/ru/post/1768873/


All Articles