Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique foreign key pairs with Django

Tags:

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.

like image 912
Thodril Avatar asked Dec 23 '10 21:12

Thodril


People also ask

Can a model have two foreign keys in Django?

First of all, anything is possible. Models can have multiple foreign keys.

Does Django index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

How does Django store ForeignKey values?

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.


1 Answers

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) 
like image 169
girasquid Avatar answered Oct 05 '22 11:10

girasquid