25

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

0

2 Answers 2

38

Use QuerySet.values_list and specify flat=True:

firstnames = Users.objects.values_list('firstnames', flat=True)
firstnames = list(firstnames)
Sign up to request clarification or add additional context in comments.

6 Comments

Hi falsetru,I get an error Manager object has no attribute value_list
@user3262370, It is values_list, not value_list.
I tried this with decimal values, the returned list contains strings: Decimal('50.00'), Decimal('100.00')?? How do I just get the values?
@almostabeginner, They are not strings. The representation of decimal objects looks like so. Try int(Decimal('50.00')) or float(Decimal('50.00')) according to your need.
With values_list you get a Queryset... containing a list : <QuerySet [... , ...]> So you must be aware that you can't really use your result as a list (for example add your 'list' to another list).
|
1
def get_array(Table, column):
    rows = Table.objects.values(column)
    return [row[column] for row in rows]

print get_array(Users, 'firstnames')

2 Comments

Use value_list() instead and select only the columns you need
In some abstractions, it may not make sense to limit columns. For simple use cases what you say is a good general rule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.