How to list a series of Objects Models in another model?

I'm creating a chatbot, with two Models. A Message model which will store all messages sent by all users to the bot, as raw data without filters. A second model representing a chat, which has to be private and specific to the user.

Therefore, I need to store messages within this chat, but entries related to the chat user only. So, on the one hand I have a model with one object is equal to one message, on the other hand I want a second model storing only user's content messages.

class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    room = models.CharField(max_length=1000)
    media = models.BooleanField(default=False)
    mediasrc = models.CharField(max_length=1000, default=None)

class Chat(models.Model):
    userchat = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, blank=True)
    group = models.BooleanField(default=False)
    messages = models.ManyToManyField(Message, blank=True, related_name='userchat')
    last_modified = models.DateTimeField(auto_now=True)

My issue is that this second model (the Chat's ones) is listing all existing messages. I need to specify a filter for the ManyToManyField.

Using Django relations you can get related Message objects to Chat object with simple method call:

chat = Chat.objects.get(id=1)  # get chat object of your choice
chat.messages.all()  # returns all messages - only related to that Chat object
Back to Top