Django QuerySet 与排除 &注释不返回任何结果
基于这个关于伪造计数的问题键,我有问题。这是我的模型:
class Type(models.Model):
is_bulk = models.BooleanField()
class Component(models.Model):
parent = models.ForgeinKey(Type, related_name="components")
我想编写一个具有所有类型的查询集,除了那些具有 is_bulk=True 且没有组件的查询集。如果 is_bulk=False,则应将其包括在内。如果 is_bulk=True 并且您有 1 个以上链接的组件,那么您就被包含在内。如果没有,你就被排除在外。
根据答案,我尝试了这个查询集:
Type.objects.annotate(num_components=Count('components')).exclude(is_bulk=True, num_components=0)
但它没有返回任何结果。
然而,这意味着应该有结果:
>>> [(x.is_bulk, x.num_components) for x in Type.objects.annotate(num_components=Count('components'))]
[(False, 0), (False, 0), (False, 0), (False, 0), (False, 0), (False, 0), (False, 0)]
所有 Type 对象都有 is_bulk=False 并且它们都有 0 个组件。通过阅读 .exclude(…) 文档,它应该是 NOT(is_bulk=True AND num_components=0)
,对于每种类型都应该是 True。正确的? (我在这里是否误解了,如果是这样,正确的查询集是什么)
如果不是,为什么这个查询集返回 []
,而它应该返回所有查询集?这是 Django 1.3 中的错误吗?
Based off this SO question about counting forgein keys, I have a problem. This is my models:
class Type(models.Model):
is_bulk = models.BooleanField()
class Component(models.Model):
parent = models.ForgeinKey(Type, related_name="components")
I want to write a queryset that has all types, except those that have is_bulk=True and have no components. If is_bulk=False, it should be included. If is_bulk=True and you have 1+ linked Components, then you're included. If not, you're excluded.
Based off the answer, I tried this queryset:
Type.objects.annotate(num_components=Count('components')).exclude(is_bulk=True, num_components=0)
But it returns no results.
However this implies that there should be results:
>>> [(x.is_bulk, x.num_components) for x in Type.objects.annotate(num_components=Count('components'))]
[(False, 0), (False, 0), (False, 0), (False, 0), (False, 0), (False, 0), (False, 0)]
All the Type objects have is_bulk=False and all of them have 0 Components. From reading the .exclude(…) documentation, it should be NOT(is_bulk=True AND num_components=0)
, which should be True for every Type. Right? (Have I made a misunderstanding here, if so, what's the correct queryset)
If not, why is this queryset returning []
, when it should return all of them? Is this a bug in Django 1.3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我尝试了这个例子,我认为你需要的是在你的领域声明一个
lated_name
:应该可以
更新
根据你的例子:
而我的:
我假设你没有符合您的查询集要求的对象:
您的结果:
这是我的情况的结果:
I tried this example and what you need I think is declaring a
related_name
in your field:That should do it
UPDATE
Based on your example:
And mine:
I'm assuming you don't have objects with the requirements of your queryset:
Your results:
This are the results in my case:
我已经通过将查询集更改为: 解决了这个问题:
这有效,但我不明白为什么我原来的查询集不起作用。啊好吧。
I have fixed this by changing the queryset to:
That works, but I can't see why my original one didn't. Ah well.