如何 return 两个用户之间的所有消息 - Django/Python/Chat 建筑

How to return all the message between two Users - Django/Python/Chat Building

我正在 Python 中使用 Django-Rest-Framework 构建一个简单的聊天。 我为用户和聊天创建了 GET/POST 方法。

型号

from django.db import models
from django.db.models.base import Model

class User(models.Model):

    class Meta:

        db_table = 'user'

    user_firstname = models.CharField(max_length=200)
    user_lastname = models.CharField(max_length=200)

class Chat(models.Model):

    class Meta:

        db_table = 'chat'
    
    from_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+')
    message = models.CharField(max_length=1000)
    to_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+')

序列化器

from rest_framework import serializers
from .models import User, Chat

class UserSerializer(serializers.ModelSerializer):

    class Meta:

        model = User
        fields = '__all__'

class ChatSerializer(serializers.ModelSerializer):

    class Meta:

        model = Chat
        fields = '__all__'

网址

from django.urls.conf import re_path
from . import views

urlpatterns = [
    re_path(r'^users/$', views.UserList.as_view(), name='users-list'),
    re_path(r'^chat/$', views.ChatList.as_view(), name='chat-get-list'),
    re_path(r'^chat/(?P<from_id>.+)&(?P<to_id>.+)/$', views.ChatList.as_view(), name='chat-list'),
]

浏览量

from rest_framework import generics, serializers
from .models import User, Chat
from .serializers import ChatSerializer, UserSerializer

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_queryset(self):

        queryset = User.objects.all()
        return queryset

class ChatList(generics.ListCreateAPIView):
    queryset = Chat.objects.all()
    serializer_class = ChatSerializer

    def get_queryset(self):
        queryset = Chat.objects.all()
        from_id = self.request.query_params.get('from_id')
        to_id = self.request.query_params.get('to_id')

        if from_id is not None and to_id is not None:
            queryset = Chat.objects.filter(from_message=from_id,to_message=to_id)
 #Probably my error is here, because I'm specifying the messages. I need to add something like 'to_message=to_id or from_id
        
        return queryset

问题: 当我发送消息时,我通知了一个from_id、to_id和一个消息本身,例如:

{
    "from_id":1,
    "message":"I'm sending a message to you",
    "to_id":2
},
{
    "from_id":2,
    "message":"I'm replying your message",
    "to_id":1
}

但是当我试图获取两个人之间的所有消息时,我只得到发送 from_id 到 to_id 的内容,但我还需要 return 发送的内容已回复,在该示例中为消息“我正在回复您的消息”。

我知道我的问题可能出在过滤器上,但我不知道如何用其他方式构建。

那么,如何return两个用户之间的所有消息?

要解决该问题,只需添加 views:

queryset1 = Chat.objects.filter(from_id=from_id,to_id=to_id)
queryset2 = Chat.objects.filter(from_id=to_id,to_id=from_id)
queryset =  queryset1.union(queryset2)