Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django中获取具有用户ID的ManyToManyField对象?_Python_Django - Fatal编程技术网

Python 如何在Django中获取具有用户ID的ManyToManyField对象?

Python 如何在Django中获取具有用户ID的ManyToManyField对象?,python,django,Python,Django,我有一个与Django频道的内置聊天,我创建了一个聊天模型,在那里我可以存储消息(就像一个有ID的聊天室),我想通过2个用户ID获取单个对象 我尝试了类似Chat.objects.filter(participants\uuuu in=[ID1,ID2])的方法,但它只返回他们在其中的每个聊天 def post(自我,请求): sender=UserProfile.objects.get(user\u id=request.user.id) message=request.data.get('m

我有一个与Django频道的内置聊天,我创建了一个聊天模型,在那里我可以存储消息(就像一个有ID的聊天室),我想通过2个用户ID获取单个对象

我尝试了类似Chat.objects.filter(participants\uuuu in=[ID1,ID2])的方法,但它只返回他们在其中的每个聊天

def post(自我,请求):
sender=UserProfile.objects.get(user\u id=request.user.id)
message=request.data.get('message')
post\u id=request.data.get('post\u id')
recipient\u id=request.data.get('recipient\u id')
chat\u room=chat.objects.filter(参与者\u in=[sender,receiver\u id])
课堂聊天(models.Model):
participants=models.ManyToManyField(UserProfile,related_name=“chats”)
messages=models.ManyToManyField(Message,blank=True,related_name=“messages”)
def获取房间信息(自我):
messages=self.messages.order_by('-timestamp').all()
返回[[i.text,i.sender\u id,i.link,i.post\u id]用于消息中的i]

然后,您应该在过滤后计算
参与者的数量,并检查其是否等于
2
,如:

from django.db.models import Count

chat_rooms = Chat.objects.filter(
    participiants__in=[sender, recipient_id]
).annotate(
    nparticipants=Count('participiants')
).filter(nparticipants=2)

它不起作用,使用过滤器返回一个空数组,使用GET:“聊天匹配查询不存在”。@mrkkry:然后,正如错误所说,没有这样的
聊天
对象,也没有说没有这样的
聊天
对象存在。我建议检查数据库,看看是否存在与两个给定参与者的
Chat
对象。
from django.db.models import Count

chat_rooms = Chat.objects.filter(
    participiants__in=[sender, recipient_id]
).annotate(
    nparticipants=Count('participiants')
).get(nparticipants=2)