Relating models in Django, ie Primary key to Foreign Key

From TRCCompSci - AQA Computer Science
Revision as of 08:51, 18 September 2019 by Admin (talk | contribs) (Created page with "To complete this tutorial, you must have created a Product model in the previous tutorials. =models.py= Within your app folder, find the 'models.py' file and edit it, It shou...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

To complete this tutorial, you must have created a Product model in the previous tutorials.

models.py

Within your app folder, find the 'models.py' file and edit it, It should already contain a model for 'Product'. Firstly, we are going to have 'User' as one of the foreign keys so we must import the built in 'User' model:

from django.contrib.auth.models import User

Now for the model itself, enter the following:

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'