Saturday, 10 July 2021

*Episode 15* PYTHON (Add the Categories in Base Project of Django)

 



Adding category as a many-to-one relationhip


  •  This episode covers :- 


 1) Many-to-one relationships with ForeignKey

 2) How to access related objects


  •  Setup :-

Terminal

cp -fr 15-Base-Project 17-Category-ManyToOne

cd 17-Category-ManyToOne

source ../venv/bin/activate


  •  Adding category field and model :-

     Edit myapp models.py file and add a Category class and a category field:

myapp/models.py

from django.db import models

class Category(models.Model): # < here

title = models.CharField(max_length=255, default='')

def __str__(self):

return self.title

class Flower(models.Model):

title = models.CharField(max_length=255, default='')

description = models.TextField(default='')

category = models.ForeignKey(Category, null=True, on_delet\

e=models.PROTECT) # < here

def __str__(self):

return self.title


      Edit myapp admin.py and register the Category model:

myapp/admin.py

from django.contrib import admin

from myapp.models import Flower, Category # < here

admin.site.register(Flower)

admin.site.register(Category) # < here


     Run migrations:

Terminal

python manage.py makemigrations

python manage.py migrate


     Edit the flowers and select a category for each item. You can create the referenced Category object while you are editing the Flower objects:




  •  Updating the homepage template :-

      Edit the myapp index.html template file and print out the category:

myapp/templates/myapp/index.html

<p class="card-text">{{ flower.description | truncatechars:\

100 }}</p>

<a href="#" class="card-link">{{ flower.category }}</a> <!-\

- here -->



  •  In Details :-

  •  Examining many-to-one relationships :-

     ForeignKey is a many-to-one relationship:
myapp/models.py
category = models.ForeignKey(Category, on_delete=models.PRO\
TECT, null=True)

     Categories can link to many flowers but each flower can have a reference to only one category.

     ForeignKey field requires two arguments: the related model class and on_delete option.

     The Flower model is related to Category class so we specify that as the first argument.

     on_delete=models.PROTECT prevents the deletion of a Category object if it’s referenced by a Flower object:



     You can delete categories that are not referenced by any flower.

     null=True means that an empty field will be stored as NULL in the database. This allows us to run the initial migration without specifying a default value.

  •  Accessing related objects :-

     You can access related objects the same way you access any attribute:
Dot notation

{{ flower.category }}


      If you need to get all flowers that link to a specific category, you can use _set like this:

Get related flowers

{{ category.flower_set }}


     You can test this by adding the following code inside the card div in the myapp index.html file:

myapp/templates/myapp/index.html

<div class="card">

...

<hr>

All flowers in the <strong>{{ flower.category }}</stron\

g> category:<br>

{% for c_flower in flower.category.flower_set.all %}

<a href="#" class="card-link">{{ c_flower }}</a><br>

{% endfor %}

</div>


      Use all in flower.category.flower_set.all so you have an iterable to loop through.




Summary


  •  ForeignKey is a many-to-one relationship. Another example would be a car model that has a foreignkey relationship to a brand model. Each car object can link to only one brand object like “Audi” or “Mercedes-Benz” but the brands can link to many car objects.
  •  Make sure to register the Category model in the admin.py file so you can create the referenced objects on the fly.
  • If you set null=True for a field, empty values will be stored as NULL in the database.


👈Episode 14(P).                                                                           Episode 16(P)👉
Share This Post

PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...