【发布时间】:2017-05-06 22:48:28
【问题描述】:
假设子表中存在某些内容,我打算遍历一对多关系以有效地从父表中选择所有记录。
来自models.py
class Meter(models.Model):
deal = models.ForeignKey(Deal, on_delete=models.CASCADE)
company = models.IntegerField()
class Deal(models.Model):
dealinfo = models.IntegerField()
在英语中,选择所有具有来自公司 #2 计量表的交易
在 SQL 中:
select * from Deal
where Deal.id in
(
select distinct Deal_id
from Meter
where Meter.company = 2
);
如果没有两个查询,我不知道该怎么做。我什至想不出用谷歌搜索解决方案的好方法。
我试过这个: 结果 = Deal.objects.filter(meter__company=2) 我在这里找到的: How do you access parent and children relationships through the ORM with a conditional on the parent where record child exist? 但它是一个内连接,并没有实现“唯一”短语,所以我得到了多条记录。
【问题讨论】: