16

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?

3
  • 2
    Have you tried doing Owner.objects.filter(owner_name='Operations').values_list('owner_id')[0][0]? Commented Sep 17, 2014 at 1:48
  • thanks that worked! Get another error now I'll make another question for it. Commented Sep 17, 2014 at 1:56
  • 2
    Try this Owner.objects.filter(owner_name='Operations').values_list('owner_id', flat=True)[0] Commented Sep 17, 2014 at 6:40

2 Answers 2

34

For posterity, this also works and is (in my opinion) the cleanest option of all:

Owner.objects.values_list('owner_id', flat=True).get(owner_name=owner_obj) 
Sign up to request clarification or add additional context in comments.

Comments

9

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.