Django Queryset filter get all elements

Viewed 657

My code looks like below

Extracting the tag-id from the Car class

tags = [UUID('1b2990eb-f625-4458-8878-1ab199e3e72b'), UUID('6e663259-9bf0-4e2d-8bf6-11be14218036')]

When I try the below codes :

Car.objects.filter(uuid__in=tags).values_list('id',flat=True)[0] -> Output 11

Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all()[0] -> Output :11
           
Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all() -> Output : <QuerySet [11,12]>

        

I want the output in the format of [11,12]

1 Answers

A QuerySet is iterable, and when you iterate over it, you get the items (model objects, tuples, dictionaries or scalar values). Therefore we can use list(…) function [Python-doc] to collect the elements:

list(Car.objects.filter(uuid__in=tags).values_list('id',flat=True))
Related