sirjay
sirjay

Reputation: 1766

How to filter and eliminate duplicates values in querysets?

I have table like this in Django + postgres:

____________________
| room_id | user_id |
|--------------------
| 1       | 100     |
| 1       | 101     |
| 2       | 100     |
| 2       | 102     |
| 3       | 103     |
 ...

Each room_id can be duplicated only 1 time. I need to figure out room_id where to users are. Simple way:

user_id_1 = 100
user_id_2 = 101
rooms = Room.objects.filter(users__in=[user_id_1, user_id_2])
temp = []
for room in rooms:
    if room.id in temp:
        room_id = room.id
        break
    else:
        temp.append(room.id)

But is there any sql filter way?

Upvotes: 3

Views: 81

Answers (2)

Sede
Sede

Reputation: 61225

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)

Upvotes: 3

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

Use distinct(<field name>) method

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

Upvotes: 1

Related Questions