Python Django模型查询

Python Django模型查询,python,sql,django,postgresql,Python,Sql,Django,Postgresql,我对Django查询模型有疑问。我知道如何编写简单的查询,但我不熟悉两个表的左连接。所以你能给我一些建议,让我更好地理解DJango ORM 查询 通过此查询,我得到以下结果: How many | name 0;"fghjjh" 0;"Papir" 0;"asdasdas" 0;"hhhh" 0;"Boljka" 0;"ako" 0;"asd" 0;"Čokoladne pahuljice" 0;"Mobitel" 2;"Čokolada" 我还尝试了他的Django查询: a = Cate

我对Django查询模型有疑问。我知道如何编写简单的查询,但我不熟悉两个表的左连接。所以你能给我一些建议,让我更好地理解DJango ORM

查询 通过此查询,我得到以下结果:

How many | name
0;"fghjjh"
0;"Papir"
0;"asdasdas"
0;"hhhh"
0;"Boljka"
0;"ako"
0;"asd"
0;"Čokoladne pahuljice"
0;"Mobitel"
2;"Čokolada"
我还尝试了他的Django查询:

a = Category.objects.all().annotate(Count('id__category',distinct=True)).filter(type_id=1)
但没有结果

我的模型:

models.py
如果你能帮我解决这个问题。

你应该在category\u id字段中添加一个相关名称,如:

category_id = models.ForeignKey('Category', related_name="product_services")
因此,在查询中,您可以执行以下操作:

a = Category.objects.all().annotate(Count('product_services',distinct=True)).filter(type_id=1)
然后您可以访问单个计数,如下所示:

a[0].product_services__count
a = Category.objects.all().annotate(Count('product_services',distinct=True)).filter(type_id=1)
a[0].product_services__count