0

I'm trying to do like this:

Class conversation(models.Model):
      user1, user2 =; # this is from User table
      messages = List(Message) # where Message is also a model

Class Message(models.Model):
      sender, reciever ; # this is user ID from User Model
      ...... # many other attribute
      message = TextField()

This is only a pseudo code. Anybody, please explain to me how to do this. If possible, give me a suitable tutorial link related to this. Thanks.

ecoder
  • 5
  • 5
  • Why not add conversation as a foreign key in Message model? – Daniel Reinoso May 15 '17 at 02:31
  • Actually, I don't want to use foreign key. I just want to store a list of messages in conversation table. Can I do like that???? – ecoder May 15 '17 at 02:33
  • If `Message` is a model, then you have to use a foreign key. If it some other bit of data, you could look at ArrayField to start arrays of text https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#arrayfield – Hamish May 15 '17 at 02:35
  • Not Django related, but SQL, read this: http://stackoverflow.com/questions/3070384/how-to-store-a-list-in-a-column-of-a-database-table – Daniel Reinoso May 15 '17 at 02:37
  • Can we use like this: `conversation = { user1 = A, user2 = B, Messages=[ {message1},{message2},{message3} ]} ` – ecoder May 15 '17 at 02:39
  • If you added a foreign key in Message like this `conversation = ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')` , you could do something like this to get messages from a conversation: `conversation.messages.all()`. – Daniel Reinoso May 15 '17 at 02:46
  • ok. Thanks, @DanielReinoso :). Can you provide me useful links to do this? Exclude djangoproject.com. – ecoder May 15 '17 at 02:49
  • It's as easy as I said above, what else do you need help with? – Daniel Reinoso May 15 '17 at 02:52

1 Answers1

1
Class Conversation(models.Model):
      user1, user2 =; # this is from User table
      ...... # many other attribute

Class Message(models.Model):
      sender, reciever ; # this is user ID from User Model
      ...... # many other attribute
      conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')

To see the messages of a conversation instance, you can follow the relationship backward like this

conversation = Conversation.objects.get(...)
conversation_messages = conversation.messages.all()
Daniel Reinoso
  • 366
  • 1
  • 12