[Django]-How to filter and eliminate duplicates values in querysets?

3👍

You can use .distinct and values_list to do this beautifully.

rooms = Room.objects.filter(users__in=[user_id_1, user_id_2])\
            .distinct("room_id").values_list("room_id", flat=True)

1👍

Use distinct(<field name>) method

rooms = Room.objects.filter(users__in=[user_id_1, user_id_2]).distinct('users')

Leave a comment