首页 > 解决方案 > Django: Choose from related set in db query

问题描述

I have two models Product and ProductFilter.

The ProductFilter has priority = IntegerField(...) field and active = BooleanField(...).

class ProductFilter(..):
    products = ManyToManyField('Product....)

I want to filter products with the active = True field for their ProductFilter with the highest priority.

I can choose product_filter with the highest priority:

product.filters.all().order_by('priority').last()

But this needs a for loop which multiplies number of queries.

Is it possible to do that in one Query? Maybe somehow aggregate/annotate the product_filter with the highest priority as active_filter and then

Product.objects.annotate(active_filter=Somehow annotate).filter(active_filter__active=True)

标签: pythonsqldjangopostgresqldjango-models

解决方案


推荐阅读