如何过滤和消除查询集中的重复值?

How to filter and eliminate duplicates values in querysets?

我在 Django + postgres 中有 table 这样的:

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

每个room_id只能复制1次。我需要弄清楚 room_id 用户在哪里。 简单方法:

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)

但是有没有sql过滤方式呢?

使用distinct(<field name>)方法

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

您可以使用 .distinct and values_list 来做这件事。

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