Django Annotate - 如何列出自我实例?



我正在尝试做一个 Django 注释,并希望通过过滤字段来列出一些对象实例。

我有两个模型,分别是CategoryArticle。这个Category模型有一个名为super_category的字段,这是一个选择字段,coices是"学术,其他">

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,
)

现在,这是我目前的年鉴结果:

[
{
'article_count': 716, 
'super_category': u'ACADEMIC',
'category_count': 5,
}, 
{
'article_count': 800, 
'super_category': u'OTHER',
'category_count': 2,
}
]

对此的查询:

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",
)

我想做的是,将类别添加到结果中

所以最后,我想要这样的东西:

[
{
'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,
},
...
]
}
]

现在,由于附加的"类别"与我试图注释的对象类型相同,因此我真的不知道该怎么做。

编辑

我正在使用如下序列化程序:

class SuperCategorySerialiser(BaseSerializer):
super_category = fields.CharField(read_only=True)
article_count = fields.IntegerField(read_only=True)
category_count = fields.IntegerField(read_only=True)

但请注意,我没有SuperCategory模型。

将其添加到目标序列化程序

Cattegories = CategorySerializer(read_only=True,many=True)

然后在目标序列化程序的字段中提及它

fields = ('X','Y','Categrories')

希望这对:)有所帮助

最新更新