我有两张桌子。城市,地方。
Cities:
id | name
Localities:
id | city_id | name
我可以制作一个查询来获取城市的地区列表(每个城市只有10行),还有该城市的地方数量?
我知道我可以在两个不同的查询中做到这一点。
请建议是否可以使用Django查询集完成。
型号:
class City(models.Model):
name = models.CharField(max_length=200)
class Locality(models.Model):
name = models.CharField(max_length=200)
city = models.ForeignKey(City,related_name='LocalityCity')
答案 0 :(得分:0)
select * from
( select c.id as city_id, count(l.id) as "localities count per city"
from cities as c
inner join localities as l on l.city_id = c.id ) as localities_count_per_city
inner join
( select c.id as city_id, c.name, l.name
from cities as c
inner join localities as l on l.city_id = c.id
limit 10) as localities_per_city ) as localities_per_city
on localities_count_per_city.city_id = localities_per_city.city_id
这应该按城市划分加入每个城市的各个地区。
答案 1 :(得分:0)
您应该提到模型而不是SQL表模式。您可以通过以下方式查询它们:
cities = City.objects.annotate(num_cities=Count("locality"))
for city in cities:
print(city.locality_set, city_num_cities)
答案 2 :(得分:0)
我可以制作一个查询来获取该地区的列表 城市(每个城市只有10排),也是中国各地的统计数字 那个城市?
假设您的模型是:
class Locality(models.Model):
name = models.CharField(max_length=200)
class City(models.Model):
name = models.CharField(max_length=200)
locality = models.ManyToMany(Locality)
你可以得到这样的结果:
all_cities = City.object.all()
for city in all_cities:
print('City: {} Total Localities: {}'.format(city.name, city.locality_set.count()))
for loc in city.locality_set.all():
print('\t{}'.format(loc.name))
在上面的代码段中,有两个查询正在执行 - 但django查询集已缓存,因此您可以放心每次都执行正确的查询。
如果您想立即完成,那么您需要使用聚合:
from django.db.models import Count
all_cities = City.objects.all().annotate(localities=Count('locality'))
for city in all_cities:
print('City: {} Total Localities: {}'.format(city, city.localities))