[TOC] >[success] # ORM 数量查询的三种方式 >[danger] ##### 正向查找 数量 ~~~ @override_settings(DEBUG=True) def test_filter(self): categories = Categroy.objects.filter(owner__username="wang").count() print(categories) pp(connection.queries) ~~~ >[danger] ##### 反向查找,不推荐 * 通过关联表,但 ForeignKey 关系是通过被关联表查询 ~~~ @override_settings(DEBUG=True) def test_filter(self): # categories = Categroy.objects.filter(owner__username="wang").count() user = User.objects.filter(username="wang") user = user[0] print(user.categroy_set.count()) pp(connection.queries) ~~~ >[danger]#### 反向查找可以使用 annotate(cate_count=Count('categroy')) 中的cate_count 是起别名,不是特定属性 <a href="https://yiyibooks.cn/xx/Django_1.11.6/topics/db/aggregation.html">更多<a> ~~~ @override_settings(DEBUG=True) def test_filter(self): # categories = Categroy.objects.filter(owner__username="wang").count() from django.db.models import Count user = User.objects.filter(username="wang").annotate(cate_count=Count('categroy')) user = user[0] print(user.cate_count) pp(connection.queries) ~~~