Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django queryset return single value

Tags:

python

django

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?

like image 937
whoisearth Avatar asked Sep 17 '14 01:09

whoisearth


People also ask

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is annotate in Django QuerySet?

annotate()that has been computed over the objects that are related to the objects in the QuerySet . Each argument to annotate() is an annotation that will be added to each object in the QuerySet that is returned. The aggregation functions that are provided by Django are described in Aggregation Functions below.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


2 Answers

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)
like image 176
Dan Tao Avatar answered Oct 03 '22 12:10

Dan Tao


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:

  • only()
  • values()
  • values_list()
like image 37
Eugene Yarmash Avatar answered Oct 03 '22 11:10

Eugene Yarmash