【问题标题】:select all records from the parent table assuming something is present in the child假设子表中存在某些内容,则从父表中选择所有记录
【发布时间】: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? 但它是一个内连接,并没有实现“唯一”短语,所以我得到了多条记录。

【问题讨论】:

    标签: python django


    【解决方案1】:

    我认为您正在寻找的可以使用distinct()来解决

     result = Deal.objects.filter(meter__company=2).distinct()
    

    【讨论】:

    • 谢谢!非常简洁明了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多