简体   繁体   English

Django查询获取相关集数

[英]Django Query Get Related Set Count

I am querying the db and am trying to find the count of a related set named 'item'. 我正在查询数据库,并试图找到名为“ item”的相关集合的计数。

user_lists = List.objects.filter(user=user).select_related('city','city__country')

that brings up the items I want, but to add the count of the related set, I'm adding annotate: 弹出我想要的项目,但是要添加相关集合的数量,我要添加注释:

user_lists = List.objects.filter(user=user).select_related('city','city__country').annotate(item_count=Count('item'))

However, this returns an empty query from the db. 但是,这将从数据库返回一个空查询。 Any ideas why? 有什么想法吗? I'm not getting any errors. 我没有任何错误。 Just an empty query set. 只是一个空的查询集。

Not an actual answer, just an idea on how you can investigate: check the actual query, that's being executes via print str(some_queryset.query) . 不是一个实际的答案,只是一个关于如何调查的想法:检查实际查询,该查询通过print str(some_queryset.query)执行。 Then you could try executing the query in manage.py dbshell and check the results. 然后,您可以尝试在manage.py dbshell执行查询并检查结果。

Also posting your models and db engine might be useful, as it might be related. 另外,发布模型和数据库引擎可能很有用,因为它可能是相关的。

maybe you can use count() method to count items in a QuerySet: count() 也许您可以使用count()方法对QuerySet中的项目进行计数: count()

user_lists_count = List.objects.filter(user=user).select_related('city','city__country').count()

is this working ? 这管用吗 ?

hope this is what you want. 希望这就是你想要的。

Just realized it was an issue with the item_count variable. 刚刚意识到这是item_count变量的问题。 When I used total_items it worked fine. 当我使用total_items它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM