[Fixed]-Could not understand foreign key and manytomany field in django

1đź‘Ť

In django, you can add one instance of a “variable” as a part of a table: That is a ForeignKey.

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=30)
    category = models.ForeignKey(Category)

class Category(models.Model):
    name = models.CharField(max_length=30)

Here, you will have a SQL table named “[NAME OF YOUR APP]_product” that will have two columns: “name” and “category_id”.

You will have an other table named “[NAME OF YOUR APP]_category” that will contain one column “name”.

Django will know that when you load a Product, it will have to get its category_id, and then get that element from the category table.

This is because you use a foreignkey: it is one “variable”. And it is “Many to One” because you can have many Products having the same Category.

Then you have “Many to Many”. Here you can have more than one “variable”

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=30)
    category = models.ManyToManyField(Category)

class Category(models.Model):
    name = models.CharField(max_length=30)

Here, the difference is that you will get a table named “[NAME OF YOUR APP]_product” with only one column: “name”.

Next to that, you will have a table “[NAME OF YOUR APP]_product_category”, that will have the columns “product_id” and “category_id”.

And one last table that will be “[NAME OF YOUR APP]_category” that will have one column: “name”.

The way it works is that Django will get the Product, and see that it have a ManyToMany field of Category.

It will go to “[NAME OF YOUR APP]_product_category” and get the list of ids for the product_id you need, and get them from “[NAME OF YOUR APP]_category”.

This is Many to Many because you can have a lot of Products that have each lots of different Category.

If you still don’t understand, I will edit this post to add a SQL example of what the database looks like.

(Sorry, this is not really pleasant to read and a really broad way to explain how Django handle things, but I tried to do short and simple statements.)

Leave a comment