Django 2.1注释子孙代数

时间:2018-10-08 10:12:19

标签: django django-2.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'))

1 个答案:

答案 0 :(得分: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()
))