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 :-
- Accessing related objects :-
{{ 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.





No comments:
Post a Comment
If you have any doubts. Please let me know.