简体   繁体   中英

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

Here is my models :

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)

I need to perform the join operation on multiple columns in above models. The columns are gold_item_id and gold_item_branch_id

I wrote the SQL Query :

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

在此处输入图片说明

How I can do the same query in Django queryset ?

You should look into django's select_related lookup.

Example:

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

You can try;

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')

If you want to see which query is actually executed:

results.query

There's another method to run the raw SQL using django. So, in your case, it would be like:

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

And iterate over this raw query result

for raw_result in raw_results:
    print(raw_result)

For more on performing raw SQL queries: https://docs.djangoproject.com/en/3.1/topics/db/sql/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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