[英]How to get a ManyToManyField object with user IDs in Django?
I have a little built-in Chat with Django Channels and I created a Chat model where I can store the messages (it is like a CHAT ROOM with ID) and I want to get the single object by the 2 users ID.我有一些内置的 Django 频道聊天,我创建了一个聊天模型,我可以在其中存储消息(就像一个带 ID 的聊天室),我想通过 2 个用户 ID 获取单个对象。
I tried something like Chat.objects.filter(participiants__in=[ID1,ID2]) but it just returns every single chat they are in.我尝试了 Chat.objects.filter(participiants__in=[ID1,ID2]) 之类的东西,但它只返回他们所在的每个聊天。
def post(self,request):
sender = UserProfile.objects.get(user_id=request.user.id)
message = request.data.get('message')
post_id = request.data.get('post_id')
recipient_id = request.data.get('recipient_id')
chat_room = Chat.objects.filter(participiants__in=[sender, recipient_id])
class Chat(models.Model):
participiants = models.ManyToManyField(UserProfile, related_name="chats")
messages = models.ManyToManyField(Message, blank=True, related_name="messages")
def get_room_messages(self):
messages = self.messages.order_by('-timestamp').all()
return [[i.text,i.sender_id,i.link,i.post_id] for i in messages]
You should then count the number of participants
after filtering, and check if that is equal to 2
, like:然后您应该计算过滤后的
participants
数量,并检查它是否等于2
,例如:
from django.db.models import
Count
chat_rooms = Chat.objects.filter(
participiants__in=[sender, recipient_id]
).annotate(
nparticipants=Count('participiants')
).filter(
nparticipants=2)
If there is exactly one such Chat
object, you can use .get(..)
instead:如果只有一个这样的
Chat
对象,您可以使用.get(..)
代替:
from django.db.models import Count
chat_rooms = Chat.objects.filter(
participiants__in=[sender, recipient_id]
).annotate(
nparticipants=Count('participiants')
)
.get(nparticipants=2
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.