In the example below, I have two models with a ManyToMany relation and I'm trying to count the number of posts related to the tags.
There are 3 tags: Sports, Films, Health
There are 3 posts: 1 for Sports, 1 for Films and 1 post with two tags (Sports and Health)
I can get the count of posts for every tag as below:
[
{
"name": "Sports",
"posts": 2
},
{
"name": "Films",
"posts": 1
},
{
"name": "Health",
"posts": 1
}
]
My requirement is to count the objects separately for the combination of tags. So, the desirable output is:
[
{
"name": "Sports",
"posts": 1
},
{
"name": "Films",
"posts": 1
},
{
"name": "Sports & Health",
"posts": 1
}
]
This is where I'm stuck. How do I combine the two tags and then count the number of post objects that have both these tags?
models.py
class Tag(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.title
serializers.py
class TagSerializer(serializers.ModelSerializer):
posts = serializers.SerializerMethodField()
class Meta:
model = Tag
fields = ('name', 'posts')
def get_posts(self, obj):
posts = obj.post_set.all().count()
return posts
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'