【问题标题】:How to perform the join on multiple fields in django queryset?如何在 django 查询集中的多个字段上执行连接?
【发布时间】:2021-01-21 01:14:36
【问题描述】:

这是我的模型:

class Picture(models.Model):
    picture_id = models.IntegerField(db_column='PictureID', primary_key=True)
    gold_item =models.ForeignKey(GoldItem,db_column="GoldItemID",related_name="pictures",on_delete=models.CASCADE)
    gold_item_branch = models.ForeignKey(GoldItemBranch, db_column="GoldItemBranchID", related_name="pictures", on_delete=models.CASCADE)
    code = models.CharField(db_column='Code', max_length=5, blank=True, null=True)


class GoldItemBranch(models.Model):
    gold_item_branch_id = models.IntegerField(db_column='GoldItemBranchID', primary_key=True)
    gold_item_id = models.IntegerField(db_column='GoldItemID')
    gold_item_branch_name = models.CharField(db_column='GoldItemBranchName', max_length=30, blank=True, null=True)

我需要对上述模型中的多个列执行连接操作。列是 gold_item_id 和 gold_item_branch_id

我写了 SQL 查询:

select * from Pictures 
join GoldItemBranches on Pictures.GoldItemID = GoldItemBranches.GoldItemID and Pictures.GoldItemBranchID = GoldItemBranches.GoldItemBranchID

如何在 Django 查询集中执行相同的查询?

【问题讨论】:

    标签: python sql django django-queryset


    【解决方案1】:

    您应该查看 django 的 select_related 查找。

    例子:

    Picture.objects.select_related('gold_item__gold_item_id').filter(gold_item_branch=gold_item_id)

    【讨论】:

    • 值得一提:没有select_related你也可以在惰性模式下访问相关字段
    • @DINOLIN 它不会给出与我在 SQL 查询中提到的相同的结果,!,谢谢
    【解决方案2】:

    你可以试试;

    ids_list = GoldItemBranch.objects.all().values_list('id', flat=True)
    results = Picture.objects.filter(gold_item__id__in = ids_list).select_related('gold_item_branch')
    

    如果要查看实际执行的是哪个查询:

    results.query
    

    还有另一种使用 django 运行原始 SQL 的方法。所以,在你的情况下,它会像:

    raw_results = Picture.objects.raw('''select * from Pictures 
                           join GoldItemBranches 
                           on Pictures.GoldItemID = GoldItemBranches.GoldItemID 
                           and Pictures.GoldItemBranchID = GoldItemBranches.GoldItemBranchID''')
    

    并遍历这个原始查询结果

    for raw_result in raw_results:
        print(raw_result)
    

    有关执行原始 SQL 查询的更多信息:https://docs.djangoproject.com/en/3.1/topics/db/sql/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 2023-03-12
    • 2022-11-01
    • 1970-01-01
    • 2010-10-26
    • 2016-08-20
    • 2018-06-09
    • 2019-08-05
    相关资源
    最近更新 更多