I'm trying to do a Django annotate and want to list some of the object instances by filtering a field.
I have two model, which is Category
and Article
. This Category
model has a field called super_category
which is a choice field and the coices are "ACADEMIC, OTHER"
class Category(models.Model):
name = models.CharField(
max_length=128,
null=False,
blank=False,
default=None,
verbose_name=_("Name"),
)
super_category = models.CharField(
blank=False,
null=False,
choices=SC_CHOICES,
max_length=10,
default=None,
)
And now, this is my current annatation result:
[
{
'article_count': 716,
'super_category': u'ACADEMIC',
'category_count': 5,
},
{
'article_count': 800,
'super_category': u'OTHER',
'category_count': 2,
}
]
the query for this :
Category.objects.only(
"id",
"articles__id",
"super_category",
).values(
"super_category",
).annotate(
category_count=Count("id", distinct=True),
article_count=Count("articles"),
).order_by(
"super_category",
)
What I wanna do is, adding the categories to the result
So at the end, I want something like this:
[
{
'article_count': 716,
'super_category': u'ACADEMIC',
'category_count': 5,
'categories': [
{
"id": 1,
"name": "COMPUTER SCIENCE",
"article_count": 15,
},
...
]
},
{
'article_count': 800,
'super_category': u'OTHER',
'category_count': 2,
'categories': [
{
"id": 1,
"name": "MAGAZINE",
"article_count": 15,
},
...
]
}
]
Now, since the additional "categories" is the same object type which I am trying to annotate, I seriously do not know how to do it.
Edit:
I am using a serializer as following:
class SuperCategorySerialiser(BaseSerializer):
super_category = fields.CharField(read_only=True)
article_count = fields.IntegerField(read_only=True)
category_count = fields.IntegerField(read_only=True)
But note that I DO NOT have SuperCategory
model.