我有聊天和参与者模型。
class Chat(models.Model):
...
class Participant(models.Model):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='participants')
participant = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
...
我正在寻找一种方法来检查是否存在与两个指定用户的单个聊天。
编辑:我曾经考虑过在嵌套对象上使用“ in”,但是不确定如何同时使用这两个对象。
qs = Chat.objects.filter(participants__participant__in[user_a,user_b])
此查询选择参与者参加的每个聊天,但我只希望两个参与者都参加的聊天
答案 0 :(得分:0)
下面是可在所需视图或模型定义中使用的查询。
在第一个查询集中使用chat__pk过滤聊天用户B
qs_first = Chat.objects.filter(
participants__participant = user_a).values('pk')
qs_second = Chat.objects.filter( pk__in = qs_first,
participants__participant = user_b)
这是因为考虑到user_a和user_b是 CustomUser 类的对象。
答案 1 :(得分:0)
您可以将呼叫链接到filter
,这将and
您的过滤条件:
qs = Chat.objects.filter(
participants__participant=user_a
).filter(
participants__participant=user_b
)