Consider:
>>>jr.operators.values_list('id') [(1,), (2,), (3,)]
How does one simplify further to:
['1', '2', '3']
The purpose:
class ActivityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ActivityForm, self).__init__(*args, **kwargs) if self.initial['job_record']: jr = JobRecord.objects.get(pk=self.initial['job_record']) # Operators self.fields['operators'].queryset = jr.operators # select all operators by default self.initial['operators'] = jr.operators.values_list('id') # refined as above.
Django queryset can be converted to a list using the python's built-in list method (list(queryset. objects. all())) but note that it is not ideal to load the whole result into memory via list() in terms of memory and time optimization.
"values()" returns a QuerySet of dictionaries. "values_list()" returns a QuerySet of tuples.
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. In this tutorial we will be querying data from the Members table.
Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.
Use the flat=True
construct of the django queryset: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list
From the example in the docs:
>>> Entry.objects.values_list('id', flat=True).order_by('id') [1, 2, 3, ...]
You need to do ..to get this output ['1', '2', '3']
map(str, Entry.objects.values_list('id', flat=True).order_by('id'))
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