Django 查询在 Deep 中设置并排除
我有三节课 产品有很多描述,每个型号都有很多商店 我想做的事
select all products but store.qty value > 0
我已经尝试过
pr = Product.objects.all().exclude(Product__Product_description__qty > 0)
我该怎么做?
class Product
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class Product_description
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
product = models.ForeignKey(Product)
class Store
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
desc = models.ForeignKey(Product_description)
qty = models.IntegerField()
i have three classes
Product have many Descriptions and each model have many stores
what i want to do
select all products but store.qty value > 0
I've tried
pr = Product.objects.all().exclude(Product__Product_description__qty > 0)
how can i do that ?
class Product
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class Product_description
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
product = models.ForeignKey(Product)
class Store
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
desc = models.ForeignKey(Product_description)
qty = models.IntegerField()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
或者,如果您确实必须使用排除:
在这两种情况下都不需要
all()
;您最终只是构建了一个未触发的代理,该代理随后用于构建过滤/排除查询集。它会浪费内存和CPU,但除此之外什么也不做。只有.delete()
运算符需要有效的all()
查询集,但这是一种专门设计的特殊情况,旨在避免意外破坏数据集。Django Queryset API 文档非常可读。
Django 约定是将您的类命名为
ProductDescription
。这看起来像是一个落后的等级制度。为什么商店会有“产品说明”?那不就是产品本身的元数据吗,而你关心的是商店有一定数量的产品吗?或者这些产品是变体,即您想要查找商店中至少有一种绿色、蓝色或橙色产品的所有产品?有件事告诉我,你的项目需要仔细重新思考。
Or if you really must use exclude:
all()
is not necessary in either case; you just end up building an untriggered proxy that goes into building the filter/exclude queryset afterward. It wastes memory and CPU, but otherwise does nothing. Only the.delete()
operator requires a workingall()
queryset, but it's a special case designed explicitly to avoid the accidental destruction of datasets.The Django Queryset API documentation is very readable.
Django convention is to name your class
ProductDescription
.This seems like a backward hierarchy. Why would stores have "product descriptions?" Isn't that metadata on the product itself, and what you care about is that the stores have a certain quantity of product? Or are these product variants, i.e you want to find all the products for which stores have at least one green or blue or orange one? Something tells me that your project needs a careful re-think.