Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how do I select a particular column from a model?

Tags:

django

I had a sniff around SO and couldn't find this, but I am sure it is here somewhere. Apologies for this potential double post!

If I have this code:

return Story.objects.filter(user=request.user.id).order_by('-create_date')

and say Story has, um, a "description" field, and I just want that description field, no need for the db to send anything else back with my result, how do I limit the query to just that?

That is, how do I generate this SQL:

select description from story where user_id = x order by create_date desc

(where x is the request.user.id value, of course)

like image 528
bharal Avatar asked May 22 '12 15:05

bharal


People also ask

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.


2 Answers

Use values() or values_list().

If you use values(), You'll end up with a list of dictionaries (technically a ValuesQuerySet)

instance = MyModel.objects.values('description')[0]
description = instance['description']

If you use values_list(), you'll end up with a list of tuples

instance = MyModel.objects.values_list('description')[0]
description = instance[0]

Or if you're just getting one value like in this case, you can use the flat=True kwarg with values_list to get a simple list of values

description = MyModel.objects.values_list('description', flat=True)[0]

See the official documentation

like image 58
Chris Pratt Avatar answered Oct 02 '22 15:10

Chris Pratt


Use the only method. Please read the documentation

like image 20
Goin Avatar answered Oct 02 '22 15:10

Goin