Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading