kamalbanga
kamalbanga

Reputation: 2011

Django OneToOneField or ForeignKey?

My models.py:

class User:
  // fields ...

class Post:
  // fields ...

class Comment:
  news = models.ForeignKey(Post)
  user = models.???(User)

Each Post can have any number of Comments. But for each Post, I want a user to have only one Comment. How do I model this?

I cannot do user = models.OneToOneField(User) because in that case a User will be able to comment only once across all Posts.

Also I cannot do user = models.ForeignKey(User) because in that case a User will be able to post as many comments as he likes on a single Post which is not what I want.

Upvotes: 1

Views: 167

Answers (1)

Wtower
Wtower

Reputation: 19902

You are interested in the unique_together model meta option:

Sets of field names that, taken together, must be unique.

class Comment(models.Model):
    news = models.ForeignKey(Post)
    user = models.ForeignKey(User)
    # ...
    class Meta:
        unique_together = ('news', 'user')

Your user field can then be simply a ForeignKey.

Upvotes: 3

Related Questions