django models relationship how to link a models A twice to model B

1118 views django
0

Let say i'm implementing a messaging service using django so i have 2 models 1 for messages and the second for users.
A message sender is a user's model instance and the message receiver also is a user's model instance.
is it a right way to do like this ?

class User(models.Model):
    first_name = models.CharField(max_length=40, default='', null=True)
    last_name = models.CharField(max_length=40, default='', null=True)

class Message(models.Model):
    sender = models.ForeignKey(User)
    receiver = models.ForeignKey(User)
    message = models.CharField(max_length=5000)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True)

Thanks

answered question

Apart from the fact you'll need add a related_name to the foreign keys - which Django will tell you when you try to run it - this looks fine. What's your question?

@lansanalsm Yes, its the right way, just add related_name in fields of Message table to make it easier to figure out sender and receiver of a message. You can read more here : docs.djangoproject.com/en/2.1/ref/models/fields/…

1 Answer

7

Yes, although you will need to change the related_name, since now this will error because there are two (implicit) relations from a User to Messages, furthermore you will need to specify what to do in case the sender and receiver are removed (you can remove the related messages as well, by specifying models.CASCADE, or another strategy [Django-doc]):

class Message(models.Model):
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='sent_messages'
    )
    receiver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='received_messages'
    )
    message = models.CharField(max_length=5000)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True)

posted this

Have an answer?

JD

Please login first before posting an answer.