Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a django queryset into an array

i would like convert a django queryset into an array like,

firstnames=Users.objects.values('firstnames')

to get a result that looks like

firstnames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne"];

Any insights please? Regards Josh

like image 853
Joshua Avatar asked Feb 21 '14 23:02

Joshua


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.

Is a QuerySet a list?

A QuerySet is a collection of data from a database. 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.

What does Values_list return in Django?

The values_list() method allows you to return only the columns that you specify.

How does QuerySet work in Django?

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT .


1 Answers

Use QuerySet.values_list and specify flat=True:

firstnames = Users.objects.values_list('firstnames', flat=True)
firstnames = list(firstnames)
like image 121
falsetru Avatar answered Oct 02 '22 04:10

falsetru