Many-to-Many Relationships
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
tags = models.ManyToManyField(Tag, related_name="posts")# Import your models
from yourapp.models import Post
# Assuming you have a post with the ID 1
post = Post.objects.get(id=1)
# Access the tags associated with the post using the related_name "posts"
tags = post.tags.all()
# Loop through and print the names of the tags
for tag in tags:
print(tag.name)Last updated