25

I have three models: products, users, and reviews.

A review is linked to a product and a user as follows:

class Review(models.Model):
    product = models.ForeignKey(Product)    
    user = models.ForeignKey(User)
    review_text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)

I'd like to allow each user to submit only one review per product. What is the recommended way to achieve this? Through the model, through verification, or something else? I'm very new to Django/Python. Thanks.

1 Answer 1

34

Use unique_together to make sure that each user/product combination is unique:

class Review(models.Model):

  class Meta:

    unique_together = ['user', 'product']

  user = models.ForeignKey(User)
  product = models.ForeignKey(Product)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.