Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django: Creating a simpler list from values_list()

Tags:

python

django

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. 
like image 377
Antonius Common Avatar asked Mar 30 '09 23:03

Antonius Common


People also ask

How do I change a QuerySet to a list in Python?

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.

What is the difference between values and values_list in Django?

"values()" returns a QuerySet of dictionaries. "values_list()" returns a QuerySet of tuples.

Is a QuerySet a list?

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.

What is values_list Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.


2 Answers

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, ...] 
like image 195
Jarret Hardie Avatar answered Oct 06 '22 06:10

Jarret Hardie


You need to do ..to get this output ['1', '2', '3']

map(str, Entry.objects.values_list('id', flat=True).order_by('id'))

like image 42
Manjunath Raddi Avatar answered Oct 06 '22 06:10

Manjunath Raddi