Relating models in Django, ie Primary key to Foreign Key

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

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

Within your app folder, find the '' 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
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils import timezone

The other imports will allow validation of numerical fields, and to also get the current time. 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( )

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

Register the Model

Now in the same folder as the '' find the ''. It should currently have this code:

from django.contrib import admin
from .models import Product

We now need to register the 'Review' model, so alter the code to this:

from django.contrib import admin
from .models import Product, Review

Now using the admin program, you will need to run the manage, and then makemigrations. You will then need to do the same and this time run migrate.

Checking your model

run the server and visit http:\\ and you should see your web app. In the address bar add '/admin' and login. You should see you model listed on the dashboard. You should be able to create new entries from this admin dashboard.

The Form

You will need to import your model into the '':

from .models import Product

Your django form should be able to use the 'ModelChoiceField' component. You need to create a queryset from your model, for example:

product = forms.ModelChoiceField(queryset=Product.objects.all(), empty_label="Please Select")

We should not include the user/author field because if we did it could be changed in the form.

The View

When you process the form, the form will be valid but still fail to save. This is because we missed out the user/author field.

So in the and the method to process the review you need to add the following to the 'if form.is_valid':

if form.is_valid:
    temp =
    temp.user = request.user
    messages.success(request, f'Your post has been successfully edited')
    return redirect('/')