backend/django

Django: filter queryset with m2m - using annotate

seul chan 2018. 4. 28. 08:30

When filter queryset using ManyToManyField, it takes too much sql queries.

For avoid this situation, we can use annotate.

Count

With django.db.models.Count, you can count number of m2m objects.

For example, if want to filter queryset having more than one ManyToManyField called product (for example)

from django.db.models import Count
...
queryset = queryset.annotate(product_num=Count('product')).filter(price_num__gte=2)
...

MinMax

It gives m2m object with minimum or maximum value.

If you want to filter queryset with m2m product having biggest price,

from django.db.models import Min, Max
...
queryset = queryset.annotate(max_price=models.Min('product__price')).filter(max_price__gte=50000)


'backend > django' 카테고리의 다른 글

Django: reset migrations  (0) 2018.04.30
Django: custom list_filter in ModelAdmin  (0) 2018.04.29
Django: overriding admin css in django  (0) 2018.04.27
Django: overriding 403 page  (0) 2018.04.26
Using Environment variable in uswgi.ini  (0) 2018.04.22