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.
如何使用名为product_name的产品获取商店,并获取所有产品(名称为product_name的产品除外)?是否可以在一个查询中进行?在原始SQL中,它将是简单的JOIN。不知道如何通过Django实现它。
3 个解决方案
#1
16
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:
你可以用Django实际做这些事情,因为它是懒惰的查询集评估。 Django的字段查找接受列表和查询集。以下将创建嵌套的SQL代码:
products = Product.objects.filter(store_set__in=stores_qs)
stores_qs = Store.objects.filter(product__name='product_name')
Here are the Django in
docs.
这是文档中的Django。
#2
5
You should be able to filter the stores based on an attribute of Product, and then prefetch_related of the retrieved objects.
您应该能够根据Product的属性过滤存储,然后prefetch_related检索到的对象。
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.
可在此处找到更多文档。
#3
1
Get Stores with product named "product_name" :
使用名为“product_name”的产品获取商店:
Store.objects.filter(product__name='product_name')
Get all the products except the product with name "product_name":
获取名称为“product_name”的产品以外的所有产品:
Product.objects.exclude(name='product_name')
#1
16
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:
你可以用Django实际做这些事情,因为它是懒惰的查询集评估。 Django的字段查找接受列表和查询集。以下将创建嵌套的SQL代码:
products = Product.objects.filter(store_set__in=stores_qs)
stores_qs = Store.objects.filter(product__name='product_name')
Here are the Django in
docs.
这是文档中的Django。
#2
5
You should be able to filter the stores based on an attribute of Product, and then prefetch_related of the retrieved objects.
您应该能够根据Product的属性过滤存储,然后prefetch_related检索到的对象。
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.
可在此处找到更多文档。
#3
1
Get Stores with product named "product_name" :
使用名为“product_name”的产品获取商店:
Store.objects.filter(product__name='product_name')
Get all the products except the product with name "product_name":
获取名称为“product_name”的产品以外的所有产品:
Product.objects.exclude(name='product_name')