【发布时间】:2017-08-01 12:50:04
【问题描述】:
这是我的模型:
class Category(models.Model):
.....
slug = models.SlugField(verbose_name=_('Slug'))
description = RedactorField(verbose_name=_('Description'))
parent = models.ForeignKey('self', null=True, blank=True,
default=None, verbose_name=_('Parent'))
问题是我需要使用 DjangoRestFramework 创建一个 api 资源,并且序列化程序应该包含每个类别的子项计数。 像这样的东西,我用generics.ListAPIView等收件箱DRF工具制作:
[
{
"id": 1,
"created": "01-08-2017 10:42 UTC",
"modified": "01-08-2017 10:55 UTC",
"name": "Category_1",
"slug": "",
"description": "",
"parent": null,
"child_count": 12,
},
{
"id": 2,
"created": "01-08-2017 10:42 UTC",
"modified": "01-08-2017 10:55 UTC",
"name": "SubCategory_1_1",
"slug": "",
"description": "",
"parent": 1,
"child_count": 0,
},
...
]
所以查询集
Category.objects.annotate(child_count=models.Count('parent'))
只会显示父母的数量(它总是等于 1 或 0)。
有 MPTTModel 库,可能可以解决这个问题,但我不能使用它,因为存在一些项目特定的问题。
【问题讨论】:
标签: django django-rest-framework serialization