Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many and how to get a queryset from queryset

I have following models:

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

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

How to get Stores with product named product_name and also, get all the products (except the product with name product_name) ? Is it possible to make it in one query? In raw SQL it would be simple JOINs. Not sure how to implement it via Django.

like image 534
sunprophit Avatar asked Feb 17 '13 00:02

sunprophit


People also ask

How do I get QuerySet in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...

How you combine multiple QuerySet in a view?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

How do you query many-to-many fields?

When querying many-to-many relationships, avoid using multiple filter() methods, make use of Q() objects instead. You can check the SQL query of a QuerySet with str(queryset. query) . Check the performance of recently executed SQL queries with django.

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.


1 Answers

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.

like image 185
miki725 Avatar answered Sep 21 '22 20:09

miki725