【问题标题】:How to make a left join in django queryset如何在 django 查询集中进行左连接
【发布时间】:2022-01-14 14:09:47
【问题描述】:

我有两个模型,我需要做一个左连接操作 我尝试了一些解决方案,但还没有成功

型号

class SmdRepairIn(models.Model):
    sum_ymd = models.DateField(blank=True, null=True)
    line_nm = models.CharField(max_length=20, blank=True, null=True)
    model_code = models.CharField(max_length=20, blank=True, null=True)

class SmdRepairOut(models.Model):  
    repair_in_id = models.CharField(max_length=20, blank=True, null=True)  
    repairman_out = models.CharField(max_length=30, blank=True, null=True)

SMDRepairIn.id == SmdRepairOut.repair_in_id

我要检索对应的查询结果:

select A.*, B.repairman_out 
from SmdRepairIn as A
     left join (select repairman_out from SmdRepairOut) B on (A.id = B.repair_in_id )

在django查询集中怎么做?

预期的结果应该是:

id、sum_ymd、line_nm、model_code、repairmain_out

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    您应该在模型中使用Foreignkey

    class SmdRepairIn(models.Model):
        sum_ymd = models.DateField(blank=True, null=True)
        line_nm = models.CharField(max_length=20, blank=True, null=True)
        model_code = models.CharField(max_length=20, blank=True, null=True)
    
    class SmdRepairOut(models.Model):  
        repair_in = models.ForeignKey(SmdRepairIn, blank=True, null=True, on_delete=models.SET_NULL)  
        repairman_out = models.CharField(max_length=30, blank=True, null=True)
    

    (注意:你应该重新考虑是否存在没有 SmdRepairIn 的 SmdRepairOut。如果没有,ForeignKey 行应该是repair_in = models.ForeignKey(SmdRepairIn, on_delete=models.CASCADE)

    这将允许您查询所需的选择。例子见这里:https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/

    一些例子:

    SmdRepairIn.objects.all().values_list('sum_ymd', 'line_nm', 'model_code', 'smdrepairout__repairman_out')
    

    这与您的要求接近。它使用反向查找smdrepairout__repairman_out

    其他方式:

    SmdRepairOut.objects.all().values_list('repairman_out', 'repair_in__sum_ymd')
    

    【讨论】:

    • 谢谢@Nechoj
    猜你喜欢
    • 2022-01-05
    • 2017-06-30
    • 2011-09-23
    • 2018-08-17
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多