简体   繁体   中英

django queryset return single value

I have the following -

obj.owner_id = Owner.objects.filter(owner_name=owner_obj).values_list('owner_id')[0]

Problem is the value it's returning is a tuple. Specifically this -

(786,)

All I want to return is the integer value or 786 .

What am I doing wrong?

对于后代来说,这也是可行的,并且(在我看来)是所有方法中最干净的选择:

Owner.objects.values_list('owner_id', flat=True).get(owner_name=owner_obj)

Assuming owner_name is unique, either of these will do the trick:

  • owner_id = Owner.objects.only('owner_id').get(owner_name=owner_name).owner_id
  • owner_id = Owner.objects.values('owner_id').get(owner_name=owner_name)['owner_id']
  • owner_id = Owner.objects.values_list('owner_id', flat=True).get(owner_name=owner_name)

Documentation:

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