[Fixed]-Django queryset return single value

33👍

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)

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:

Leave a comment