Skip to content

Django queryset to list of ids with integer values

I need to retrieve IDs from multiple queries and add them into a list.

products = Product.objects.filter(category="Apple").values_list("product_id", flat=True)

reviewed = Reviews.objects.filter(category="Apple").values_list("product_id", flat=True)

selected_ids = [10,20,30]

Then I tried

all_products = selected_ids + products + reviewed

This raised error as list cannot be added to queryset.

so, I tried,

all_product_ids = selected_ids + list(products) + list(reviewed)

This works but, all_products has a mix of int and tuple values [10, 20, 30, (2,), (2,), (1,)]

I need them to be [10, 20, 30, 2, 2, 1]



You can use union and then add them with the list:

qset_ids = Product.objects.filter(category="Apple").values_list("product_id").union(Reviews.objects.filter(category="Apple").values_list("product_id"))

all_product_ids = selected_ids + list(qset_ids.values_list('product_id',flat=True))
User contributions licensed under: CC BY-SA
6 People found this is helpful