1

我想计算每条记录有多少子孙。这些是我的表结构如下:

记录:

id  | name
1   | record 1

帖子:

id  | record   | title
1   | record 1 | title 1
2   | record 1 | title 2

附件:

   id   | post   | name
   1    | post 1 | name 1
   2    | post 1 | name 2
   3    | post 2 | name 3

所以通过这个例子记录 1 应该有

   children: 2
   grandchildren: 3
   total_links: 5 

这是我在 view.py 中的当前代码:

records = Record.ojects.all().annotate(total_links=Count('post__id'))
4

1 回答 1

0
queryset = Record.ojects.all().annotate( 
                post_count=Count('post'), 
                attachment_count=Count('post__attachment'))

records = queryset.annotate(children_count= ExpressionWrapper(
                             F('post_count') + 
                             F('attachment_count'),
                             output_field=DecimalField()
))
于 2018-10-08T11:36:42.870 回答