11👍
✅
Why not a simple list comprehension?
qs = UnitTestCollection.objects.filter(unit__type=unit_type)
my_values = [item.field_name for item in qs]
Or use values_list()
to just fetch the specific field for each item directly in your queryset, with the advantage of lazy evaluation:
qs = UnitTestCollection.objects.filter(unit__type=unit_type)\
.values_list('field_name', flat=True)
0👍
values_list
is better than a list comprehension because querysets are lazily evaluated. They won’t be executed until you actually need them.
queryset = UnitTestCollection.objects.filter(unit__type=unit_type).values_list('<insert field>', flat=True)
This will return [field1, field2, field3...]
if you use .values('<insert field>')
you’ll get [{field: field value1}, {field: field value2}, {field: field value3}...]
- [Django]-How to use a different database for Heroku review apps?
- [Django]-Deploying Django application on Webfaction
- [Django]-Django.db.utils.InterfaceError: (0, '')
- [Django]-Create Docker container with Django, npm and gulp
- [Django]-ImageField Django template
Source:stackexchange.com