简体   繁体   中英

Django-Taggit | Getting ALL tags, but only related to blog

I am using django-taggit to tag three different types of models:

  • a blog
  • a list of events
  • a list of products.

This all works fine.

I am now trying to grab a list of all the available tags related to the blog so I can display them on the BlogIndex page. The furthest I've gotten is, thanks to a similar SO question:

from taggit.models import Tag

def blog_tags(self):
    tags = Tag.objects.all()
    return tags

However this gives me a list of every single tag, including the product and event tags.

How do I filter that list of tags down to just the blog?

EDIT | modely.py simplified:

class BlogPostTag(TaggedItemBase):
    content_object = ParentalKey('BlogPost', related_name='tagged_items')

class BlogPost(Page):
    # my fields
    tags = ClusterTaggableManager(through=BlogPostTag, blank=True)

    # Getting BlogPost-specific tags here is not difficult

class BlogIndex(Page):
    # my fields

    def blog_tags(self):
        etc...

If tags are directly put on your Blog object (that I'll call here myBlog ) and you want to fetch all of them, here's what you can do :

myBlog.tags.all()

However, this might not be what you're looking for : please do post the code related to your models.

EDIT.

What I gather from the code is that you tag your blog posts with a custom class BlogPostTag that inherits TaggedItemBase , an abstract class that looks like this :

class TaggedItemBase(ItemBase):
      tag = models.ForeignKey(Tag, 
        related_name="%(app_label)s_%(class)s_items", on_delete=models.CASCADE)

I can't test it because there's not enough code, but I think you might be able to fetch all the tags on your blog posts by doing something like this :

  BlogPostTag.objects.all().values('tag')

Keep us posted! Thank you :-)

For anyone else looking for an answer to this question, I found a simple workaround:

def blog_tags(self):
    tags = BlogPost.tags.most_common()
    return tags

This lists all the tags associated with the BlogPost model in order of most used to least used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM