Question

I am trying to write a simple messages system.

Basically I have a User table and a Message table.

class User(models.Model):
   user = models.OneToOneField(User)# inherit djangos default user properties
   messages = models.ManyToManyField(Message)

.

class Message(models.Model):
   date = models.DateField()
   text = models.CharField(max_length=255)
   user = models.ManyToManyField(User)

I want to be able to add as many users to as many messages as possible.

I want to be able to say messages.users and users.messages.

What is the best way to accomplish this?

Was it helpful?

Solution

You shouldn't define the relationship on both sides. Pick one - probably Messages - and define it there. Django automatically provides the reverse relationship.

Also, you don't need a separate User class, especially if the M2M field is on messages itself. So, you can just do this:

class Message(models.Model):
   date = models.DateField()
   text = models.CharField(max_length=255)
   users = models.ManyToManyField('auth.User')

And now you can access the messages for a user with my_user.message_set.all(), and the users for a message with my_messages.users.all().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top