我有两个桌子品牌和一个产品。每个品牌都有多个产品。
所以我使用prefetch_related以最低的产品价格获得特定品牌的相关产品。但是问题是当我有两个价格相同的产品时,它同时选择了两个记录,因此如何限制此记录?
alternatives_data = Brand.objects.filter(category__category_slug = category_slug).prefetch_related(
Prefetch('products', queryset=Product.objects.annotate(
min_brand_price=Min('brand__products__product_price')
).filter(
product_price=F('min_brand_price')
).order_by('product_id')))
我尝试了一切,但无济于事!
为了防止查询返回特定列中具有重复项的多个记录,请使用distinct
方法。根据您的情况,将.distinct('price')
添加到预取内的产品查询集中。
但是有一个警告:仅PostgreSQL支持。