如何在djangoqueryset中执行多个字段的连接?

j2qf4p5b  于 2023-02-14  发布在  Go
关注(0)|答案(3)|浏览(157)

下面是我的模型:

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_分支_id
我编写了SQL查询:

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

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

qvtsj1bj

qvtsj1bj1#

你应该看看django的select_related查找。
示例:
Picture.objects.select_related('gold_item__gold_item_id').filter(gold_item_branch=gold_item_id)

ruyhziif

ruyhziif2#

你可以试试

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/

insrf1ej

insrf1ej3#

若要执行多列联接,请使用FilteredRelation。

相关问题