作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
最奇怪的是,要么是我遗漏了一些基本的东西,要么是 django 的错误
例如:
class Author(Model):
name = CharField()
class Parent(Model):
name = CharField(
class Subscription(Model):
parent = ForeignKey(Parent, related_name='subscriptions')
class Book(Model):
name = CharField()
good_book = BooleanField()
author = ForeignKey(Author, related_name='books')
class AggregatePerson(Model):
author = OneToOneField(Author, related_name='+')
parent = OneToOneField(Parent, related_name='+')
当我尝试时:
AggregatePerson.objects.annotate(counter=Count('author__books')).order_by('counter')
一切正常。如果我添加以下内容,则排序和字段 counter
和 existing_subs
都显示正确的数字但是:
AggregatePerson.objects.annotate(existing_subs=Count('parent__subscriptions')).exclude(existing_subs=0).annotate(counter=Count('author__books')).order_by('counter')
然后counter
和existing_subs
字段变成18
为什么是 18 岁?我做错了什么?
感谢您的帮助!
编辑进一步研究后的澄清:
counter
也得到了existing_subs
最佳答案
我找到了这个问题的答案。
我;博士:
您需要像这样在 Count
中添加 distinct=True
:
AggregatePerson.objects.annotate(counter=Count('author__books', distinct=True))
更长的版本:
添加一个 Count
注释就是添加一个 LEFT OUTER JOIN在幕后。由于我们添加了两个注释,它们都引用同一个表,因此 selected 和 grouped_by 行的数量增加了,因为某些行可能出现两次(一次用于第一个注释,另一个用于第二个注释),因为 LEFT OUTER JOIN 允许空单元格(行) 从右表中选择。
关于django - 多个 Django annotate Count over reverse relation of a foreign key with an exclude 返回一个奇怪的结果 (18),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216721/
我是一名优秀的程序员,十分优秀!