djangodjango-viewsdjango-querysetdjango-filter

Extract values from Django <QuerySet> object


I have this Python code for filtering:

x_list  = []
x = SupplierCommunication.objects.filter(supplier=supplier.id).values_list("x",flat=True)
x_list.append(x)

this code outputs this:

x_list:  [<QuerySet ['no']>, <QuerySet ['yes']>]

however I want it to be like this

x_list = ['no','yes']

How can I achive this? I have tried using .values() , .value_list() however none of it worked for me.

Any other suggestions?


Solution

  • Your items are still querysets, you iterate over these to get the values, so use .extend(..):

    x_list = []
    x = SupplierCommunication.objects.filter(supplier=supplier.id).values_list(
        'x', flat=True
    )
    x_list.extend(x)