willhelm
willhelm

Reputation: 13

Listing tags by ManyToMany relationship in django

I'm learning Django and have gone already through various tutorials. I have created a basic blog site, but wanted to add tagging funcionality. It works - I have posts with assigned tags, but I'm struggling to list those tags in the post now.

blog/models.py:

class Post(models.Model):
    title = models.CharField(max_length=50)
    text = models.CharField(max_length=1000)
    pub_date = models.DateTimeField('date published')
    author = models.CharField(max_length=30)
    mail = models.EmailField()

class Tag(models.Model):
    name = models.CharField(max_length=15)
    posts = models.ManyToManyField(Post, related_name="tags")

I know I would need something like: Tag.objects.filter() but could you please guide me how to list only those related to the specific post? I was trying various combinations, but none of them worked really well...

Upvotes: 1

Views: 908

Answers (2)

azmirfakkri
azmirfakkri

Reputation: 601

This is how I solved mine. Just slightly different from @Sagar I want to get the tags associated with my blog post.

Rather than using tags_set I use the plural form of tag, tags.

# object containing title, body etc
post = Post.objects.get(slug=slug)

# get all the tags
p = Post.objects.get(id=post.id)
tags = p.tags.all()

Upvotes: 0

Sagar
Sagar

Reputation: 1155

No of ways to achieve this.

Get Tag, Find all posts in which it is incurred.

try:
    tag = Tag.objects.get(name="#blawBlaw")
    posts_of_that_tag = tag.posts.all()
except Tag.DoesNotExist:
    pass

Other way: Get Post and Find it's tags

try:
    p = Post.Objects.get(id=1)
    tags = p.tag_set.all();
except Post.DoesNotExist:
    pass

Upvotes: 2

Related Questions