Home>
from django.db import models
from django.contrib.auth import get_user_model
#Create your models here.
User = get_user_model ()
#This is for making friends
class Contact (models.Model):
    user = models.ForeignKey (User, related_name ='friend', on_delete = models.CASCADE)
    friends = models.ManyToManyField ('self', blank = True)

    def __str __ (self):
        return self.user.name

#This is for new Messages
class Message (models.Model):
    contact = models.ForeignKey (Contact, related_name ='message', on_delete = models.CASCADE)
    content = models.TextField ()
    timestamp = models.DateTimeField (auto_now = True)
    def __str __ (self):
        return self.contact.user.name

#This is for fetching messages
class Chat (models.Model):
    participants = models.ManyToManyField (Contact, related_name ='chats')
    messages = models.ManyToManyField (Message, blank = True)

    def last_30_messages (self):
        return self.messages.objects.order_by ('-timestamp'). All () [:30]

    def __str __ (self):
        return "{}" .format (self.pk)
from django.shortcuts import render, get_object_or_404
from .models import *
def get_last_30_messages (ChatID):
    print ('ChatID ::', ChatID)
    chat = get_object_or_404 (Chat, id = ChatID)
# At this point, print (chat) =>1 and pk is returned properly
    return chat.messages.order_by ('-timestamp'). All () [:30]
     # chat.messages.order_by ('-timestamp'). All () [:30] is empty

If i check with admin, there are certainly messages.

Even if you open the Messages section and check it, it is certainly there. Even if I checked the contents, the content, name, and timestamp were in each message.

By the way, with the same Chat ID

from django.shortcuts import render, get_object_or_404
from .models import *
def get_last_30_messages (ChatID):
    print ('ChatID ::', ChatID)
    chat = get_object_or_404 (Chat, id = ChatID)
    return chat.participants.order_by ('-timestamp'). All () [:30]
#messages =>participants


Then, partials will be returned properly, but as soon as I make messages, an empty queryset will be returned.

I want to fetch the messages in the photo, is there any reason for this to happen?

  • Answer # 1

    I didn't understand how ManytoManyFields works. It was necessary not only to create a Message with create, but also to add it to Chat.

    current_chat = get_object_or_404 (Chat, id = 1)
    current_chat.messages.add (message)
    current_chat.save ()