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
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.
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.
The values_list() method allows you to return only the columns that you specify.
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 .
Use QuerySet.values_list
and specify flat=True
:
firstnames = Users.objects.values_list('firstnames', flat=True)
firstnames = list(firstnames)
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