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.
First of all, anything is possible. Models can have multiple foreign keys.
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
Note that the _id in the artist parameter, Django stores foreign keys id in a field formed by field_name plus _id so you can pass the foreign key id directly to that field without having to go to the database again to get the artist object.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With