How to return all the message between two Users - Django/Python/Chat Building
I'm building a simple chat with Django-Rest-Framework in Python. I created a GET/POST methods for Users and Chat.
MODEL
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='+')
SERIALIZERS
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__'
URLS
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'),
]
VIEWS
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
THE PROBLEM: When I send a message, I informed a from_id, to_id and a message itself, for example:
{
"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
}
But when I'm trying to get all the messages between two persons, I get just what was send from_id to to_id, but I also need to return what was replyed, in that example the message "I'm replying your message".
I know that my problem is probably in the filter, but I don't know how to build in another way.
In that case, how to return all the messages between two Users?
To resolve that problem just add at views:
queryset = Chat.objects.filter(from_message=from_id or to_id,to_message=to_id or from_id)