Home > OS >  How to get list of tags related to any Blogpost in model - Django
How to get list of tags related to any Blogpost in model - Django

Time:10-01

So I have two models:

class Tag(models.Model):
    name = models.CharField(max_length=15)

    def __str__(self):
        return str(self.name)

and

class BlogPost(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True, blank=True, null=True)
    author = models.CharField(max_length=255)
    tags = models.ManyToManyField(Tag)
    body = models.TextField(blank=True, null=True)
    snippet = models.TextField(max_length=255)
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default='draft')
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-created_on',)

    def __str__(self):
        return str(self.title)

I am trying to get a list of tags that have been used in any BlogPost model object i.e. if there are tags stored in database are ['movie','entertainment','games','documentary']

and BlogPost A has tags with m2m relation: ['movie','documentary'] and BlogPost B has tags with m2m relation:['games']

then I want to get a list of tags that has been used in any object BlogPost model as ['movie','documentary','games'].

I couldn't find the answer to this.Is there a way to query for this?

CodePudding user response:

try this if you want to have a queryset.

BlogPost.objects.all().values_list('tags__name',flat=True)

try this if you want to have a list.

list(BlogPost.objects.all().values_list('tags__name',flat=True))

try this if you want to have unique value of all tags

list(set(BlogPost.objects.all().values_list('tags__name',flat=True)))

CodePudding user response:

If you want a list in key value pairs, you may use first block of codes and if you want to unpack values from the list use second block of code.

# To get the tags in list
posts = BlogPost.objects.all()
for post in posts:
    tags = post.tags.values("name")
    print(tags) 

# To unpack the values
for post in posts:
    for tag in post.tags.all():
        print(tag.name)

For any help, let me know. Happy coding.

CodePudding user response:

I also found another solution to my question :

queryset = Tag.objects.filter(blogpost__id__isnull=False).distinct()

This way I got to use the Tag model object also and gives unique tags in queryset.

  • Related