亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對 django 查詢集中的多個字段執行聯接?

如何對 django 查詢集中的多個字段執行聯接?

婷婷同學_ 2023-10-11 20:10:26
這是我的模型: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 queryset 中執行相同的查詢?
查看完整描述

3 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

要執行多列聯接,請使用FilteredRelation。



查看完整回答
反對 回復 2023-10-11
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

您應該查看 django 的select_lated查找。

例子:

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


查看完整回答
反對 回復 2023-10-11
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

你可以試試;


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)

查看完整回答
反對 回復 2023-10-11
  • 3 回答
  • 0 關注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號