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 Store
s 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 JOIN
s. Not sure how to implement it via 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: ...
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With