Design a site like this with
Get started

P7 – Django – Relationships

So till in the previous tutorials we have different ways to configure views and models but we have seen basic examples and there were no relationships between models which hardly happen in the real world. In most cases models have relationship between each other.

Lets see how to create relationship between our product and company model. So earlier we created two models, product and company but there was no relationship between them. So ideally each product is produced by a company. So there is one to one relation between a product and company. a product is associated with one and only one company.

Step 1

Lets implement this in our models. Before starting lets flush out the data we created from our previous tutorials using the command “python flush”


Step 2

Now update our models to create the relationship between Product and Company.

We have here created a company variable in the Product model and used the ForeignKey Api to in the models class to create the relationship. We have also mentioned what should happen when a record is deleted using the on_delete parameter. In our case we do not want anything to happen in the company model when a product record is deleted. The parameter blank = False means that the field cannot be blank. There are several other parameters that we can set for a field. You can check them out at the django documentation

Update the product serializer to have company

There is no change required in the view class and also no change required in the file. Now lets see how does the database table of product look like.

See, a new column company_id is added to the product table which refers to the primary key of the company table.

Step 3

Lets add a company and try adding a product afterwards and with a company associated with it.

We add a new company

Notice that when we retrieve we receive only the company id and not the entire company object with details. Lets make a simple change to retrieve entire company object details instead of the id.

update the serializer of the product to with a reference to company serializer as below.

Now lets see the output.

We can add different relationships other than Foreign key, like the onetoone of manytomany. The implementation is similar to the above with change in the api. Rest of the things will mostly remain the same