【问题标题】:How to get count in Django for a model two foreign keys away如何在 Django 中为模型计算两个外键
【发布时间】:2021-07-28 11:30:53
【问题描述】:

我的 Django 应用中有以下三个模型:

class City(models.Model):
    city_name = models.CharField(length=50)

class Area(models.Model):
    city = models.ForeignKey(City)
    area_name = models.CharField(length=50)

class Person(models.Model):
    area = models.ForeignKey(Area)
    person_name = models.CharField(length=50)

我要求城市按人口顺序排列(即以人为基础)。用 Django 怎么可能?

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    使用annotate 统计人口数。

    City.objects.annotate(population=Count("area_set___person_set")).order_by("population")
    

    【讨论】:

    • 你好 Reza,谢谢你的回答。这并没有直接起作用,而是指向了正确的方向。这个解决方案对我有用:City.objects.annotate(population=Count('area__person')).order_by('-population')
    • ForeignKey 中有related_name 吗?
    • 不,事实并非如此。如果您查看文档,示例中未使用_set。我只是不知道它是否适用于两个外键。
    猜你喜欢
    • 2019-07-30
    • 2010-10-07
    • 2015-12-21
    • 2017-11-27
    • 2016-01-05
    • 1970-01-01
    • 2020-04-04
    • 2012-04-28
    相关资源
    最近更新 更多