简体   繁体   中英

django two filter with different key on merge with same key name

In django i have two query like:

First = User.objects.filter(id=data.get('id')).values('first_id','first_name')
Second = User.objects.filter(id=data.get('id')).values('second_id','second_name')
combined_results = list(chain(competitorFirst, competitorSecond))

After this i am getting output like:

{'first_id': '1', 'first_name': 'Hornets'}
{'second_id': '2', 'second_name': 'corto'}

what i actually want is like:

{'id': '1', 'name': 'Hornets'}
{'id': '2', 'name': 'corto'}

can anyone please help how can i solve this.

You are ultimatly chaining queryies, so why not just convert them to dictionary, normalize them and then chain them:

name_map = {'first_name': 'name', 'second_name': 'name', 'first_id': 'id', 'second_id':'id'}

def rename_dict(d):
   return dict((name_map[key], value) for (key, value) in d.items())

competitorFirst = map(rename_dict,  list(User.objects.filter(id=data.get('id')).values('first_id','first_name'))) 

competitorSecond = map(rename_dict,  list(User.objects.filter(id=data.get('id')).values('second_id','second_name')))

combined_results = list(chain(competitorFirst, competitorSecond))

Update: I think you should look into your model design, because if you have two competitors then it would be better to have a seperate table for that competion, and use combined results. For example:

class Competition(models.Model):
   first_competitor = models.ForeignKey(User, related_name='first')
   second_competitor = models.ForeignKey(User, related_name='second')

You can consider ManyToMany fields as well if you have more than two competitors.

try this:

from django.db.models import F

First = User.objects.filter(id=data.get('id')).values(id=F('first_id'), name=F('first_name'))
Second = User.objects.filter(id=data.get('id')).values(id=F('second_id'), name=F('second_name'))
combined_results = list(chain(competitorFirst, competitorSecond))

use F to set the name.

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