【发布时间】:2017-10-31 16:28:21
【问题描述】:
我使用的是 1.8 版
class ProductProduct(models.Model):
product_tmpl = models.ForeignKey(ProductTemplateModel)
default_code = models.CharField()
name_template = models.CharField()
...
class PurchaseOrder(models.Model):
# fields...
class PurchaseOrderLine(models.Model):
id = models.IntegerField()
product_id = models.ForeignKey(ProductProduct)
order_id = models.ForeignKey(PurchaseOrder)
我只需要列出 default_code(在 ProductProduct 模型中)为空的 PurchaseOrder 记录。
我无法使用“purchaseorderline_set.product_id_set.default_code=None”进行过滤 因为 purchaseorderline_set 是一个查询集,它没有属性 product_id_set 如here 所示。所以我尝试使用这个:
orders_recs = PurchaseOrder.objects.all().order_by('-id')
orders_recs = PurchaseOrder.objects.filter(purchaseorderline_set.product_id_set.default_code=None).order_by('-id')
orders = []
for order_rec in orders_recs:
line = order_rec.purchaseorderline_set.all()
if line and line[0].product_id.default_code == None:
orders.append(order_rec)
但它需要超过 3 秒。考虑到我只是一个在我的 DEV 环境中工作的人(机器并不慢)并且 DB 到目前为止非常小,因为只有 269 个 PurchaseOrder 记录、396 个 PurchaseOrderLine 记录和 726 个 ProductProduct 记录,我认为这很多。
我想有一种我没有看到的有效方法。
【问题讨论】:
标签: django foreign-keys query-performance