63👍
✅
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
- [Django]-Convert seconds to hh:mm:ss in Python
- [Django]-How do you know if memcached is doing anything?
- [Django]-Add rich text format functionality to django TextField
0👍
As the docs says if the your query set is going to yield only one object, it’s recommended that you should use get() instead of filter. From the name that you’ve given, I would assume that user_id is distinct for every user.
EDIT1 : I just took a notice of orderby clause. So I would suggest to use this code if the user_id is distinct or with pk.
description = story.objects.filter('description').get(user_id=x)
- [Django]-Render HTML to PDF in Django site
- [Django]-Test sending email without email server
- [Django]-Django rest framework: query parameters in detail_route
Source:stackexchange.com