Enforcing unique model entries

From TRCCompSci - AQA Computer Science
Revision as of 10:11, 6 October 2019 by Admin (talk | contribs) (Created page with "This will assume you have created the previous tutorial models of 'Review' and 'Products'. =the Meta section= You current 'Review' model should look something like this: <s...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This will assume you have created the previous tutorial models of 'Review' and 'Products'.

the Meta section

You current 'Review' model should look something like this:

class Review(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
    text = models.TextField()
    date = models.DateTimeField( default=timezone.now )

    def __str__(self):
        return self.author.username + ' - ' + self.product.name + ' - ' + str(self.rating) + ' out of 10'


We can define a 'Meta' section similar to other parts of these django tutorials.

class Review(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
    text = models.TextField()
    date = models.DateTimeField( default=timezone.now )

    def __str__(self):
        return self.author.username + ' - ' + self.product.name + ' - ' + str(self.rating) + ' out of 10'

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['author', 'product'], name='name of constraint')
        ]

This will ensure the combination of 'author' and 'product' is unique, this will mean an author can only review a product once. You could specify any combination of your fields to be unique.