[Fixed]-Unable to get distinct results for queryset

1๐Ÿ‘

โœ…

If you are using PostgreSQL, specify the level of distinction:

queryset = StoreProduct.objects.distinct('product')

you can also use it in conjunction with values(), order_by(), etc:

queryset = StoreProduct.objects.values('product').distinct()

I will suggest the following as solution but not the solution; either you choose PosgreSQL as database, specially that the newest Django version is coming with more built-in support for complex data structure, or you try make you own filter as follow (but in case you have large dataset this will be really bad):

store_product_id_list = StoreProduct.objects.values('product').distinct()
store_product_list = []
for obj in store_product_id_list:
    store_product_obj = StoreProduct.objects.filter(product_id=obj.get('product')).first()
    store_product_list.append(store_product_obj)

Check distinct for more examples

๐Ÿ‘คDhia

Leave a comment