繁体   English   中英

如何在 Django 查询集中的多个字段上执行连接?

[英]How to perform the join on multiple fields in django queryset?

这是我的模型:

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 查询集中执行相同的查询?

您应该查看 django 的select_related查找。

例子:

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

你可以试试;

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM