django外键的外键

时间:2015-04-05 00:08:15

标签: mysql django

我有一个rolodex示例的以下类: 我有一个问题涉及访问外键的外键。下面的代码片段:

class Country(models.Model):
    name = models.CharField(unique=True, max_length=100)
    ...

class State(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country)
    ...

class City(models.Model):
    state = models.ForeignKey('State')
    name = models.CharField(max_length=100)
    ...

class People(models.Model):
    city = models.ForeignKey(City, blank=True, null=True)
    ...

现在,我需要了解每个州(国家)的人数。我可以这样写一个SQL查询:

select s.name, count(*) as total
    from person p join city c join state s
    where p.city_id = c.id and c.state_id = s.id
    group by s.name
    order by total desc;`

这给了我每个州名和该州的人数。如何在django中执行此查询?

0 个答案:

没有答案