Reputation: 2011
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 Comment
s. 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 Post
s.
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
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