25👍
You can actually do these things with Django due to it’s lazy queryset evaluation. Django’s in
field lookup accepts both lists and querysets. The following will create a nested SQL code:
products = Product.objects.filter(store_set__in=stores_qs)
stores_qs = Store.objects.filter(product__name='product_name')
Here are the Django in
docs.
9👍
You should be able to filter the stores based on an attribute of Product, and then prefetch_related of the retrieved objects.
Store.objects.filter(product__name="product_name").prefetch_related('product')
This should hit the database the fewest times to achieve what you are looking for – twice.
Further documentation can be found here.
- How to limit choices of ForeignKey choices for Django raw_id_field
- Where do I put "WSGIPassAuthorization On"?
- Custom authentication backend. Django
- Unable to encode/decode pprint output
2👍
Get Stores with product named “product_name” :
Store.objects.filter(product__name='product_name')
Get all the products except the product with name “product_name”:
Product.objects.exclude(name='product_name')
- How to create custom groups in django from group
- Verbose_name for a model's method
- How to use custom managers in chain queries?
Source:stackexchange.com