To many many, and how to get a request from a set of requests

I have the following models:

class Store(models.Model): name = CharField(max_length=30) product = models.ManyToManyField(Product) class Product(models.Model): name = CharField(max_length=30) 

How to get a Store with a product named product_name , and also get all products (except for a product named product_name )? Is it possible to do this in one query? In raw SQL, that would be just JOIN s. Not sure how to implement it through Django.

+6
source share
3 answers

In fact, you can do this with Django because of its lazy query set evaluation. A search in Django in allows you to accept both lists and queries. The following will create the embedded SQL code:

 stores_qs = Store.objects.filter(product__name='product_name') products = Product.objects.filter(store_set__in=stores_qs) 

Here are the django in docs.

+15
source

You should be able to filter stores based on the Product attribute and then prefetch_related from the extracted objects.

 Store.objects.filter(product__name="product_name").prefetch_related('product') 

This should hit the database the least number of times to achieve what you are looking for - twice.

Further documentation can be found here .

+4
source

Get stores with a product named "product_name":

 Store.objects.filter(product__name='product_name') 

Get all products except the product named "product_name":

 Product.objects.exclude(name='product_name') 
0
source

All Articles