Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values from Django <QuerySet> in Python 3

I have some python code:

UnitTestCollection.objects.filter(unit__type=unit_type)

which outputs data in format:

<QuerySet [<UnitTestCollection: VALUE1>, <UnitTestCollection: VALUE2>...

How can I extract a list of the values only i.e.

[VALUE1, VALUE2....]
like image 887
2one Avatar asked Feb 03 '26 08:02

2one


1 Answers

Why not a simple list comprehension?

qs = UnitTestCollection.objects.filter(unit__type=unit_type)
my_values = [item.field_name for item in qs]

Or use values_list() to just fetch the specific field for each item directly in your queryset, with the advantage of lazy evaluation:

qs = UnitTestCollection.objects.filter(unit__type=unit_type)\
                               .values_list('field_name', flat=True)
like image 83
Işık Kaplan Avatar answered Feb 06 '26 02:02

Işık Kaplan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!