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?
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.
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.
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.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With