Referencing tags with a Many To Many field
This episode covers :-
1) How to reference multiple items with many-to-many relationships.
- Setup :-
Terminal
cp -fr 15-Base-Project 18-Tags-ManyToMany
cd 18-Tags-ManyToMany
source ../venv/bin/activate
- Adding the tags field :-
Edit myapp models.py file and add Tag model and tags field:
myapp/models.py
from django.db import models
class Tag(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='')
tags = models.ManyToManyField(Tag) # < here
def __str__(self):
return self.title
Edit myapp admin.py file and register the Tag model:
myapp/admin.py
from django.contrib import admin
from myapp.models import Flower, Tag # < here
admin.site.register(Flower)
admin.site.register(Tag) # < here
Run migrations:
Terminal
python manage.py makemigrations
python manage.py migrate
Edit a flower and add some tags. Make sure to select more than one tag:
- Updating the homepage template :-
Edit the myapp index.html template file and print out the tags:
myapp/templates/myapp/index.html
<div class="card">
...
<hr>
{% for tag in flower.tags.all %}
<a href="#" class="card-link">{{ tag }}</a>
{% endfor %}
</div>
- ManyToMany relationship allows our flowers to reference many tags and the tags to reference many flowers.



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