【发布时间】:2014-05-17 02:19:42
【问题描述】:
我想知道有多少地图通过 ManyToManyField 与查询集相关,或者换一种说法,有多少地图至少有一个 shapefile 作为图层。
models.py:
class Map(models.Model):
layers = models.ManyToManyField(Shapefile)
class Shapefile(models.Model):
filename = models.CharField(max_length=255)
views.py:
shapefiles = Shapefile.objects.filter(created_by=request.user)
map_instances = Map.objects... ???
示例:
shape1 = Shapefile(filename = 'shape1')
shape2 = Shapefile(filename = 'shape2')
shape3 = Shapefile(filename = 'shape3')
map1 = Map(name = 'map1')
map1.layers.add(shape1)
map1.layers.add(shape2)
map1.layers.add(shape3)
shapefiles = Shapefile.objects.all()
map_instance = [shape.map_set.count() for shape in shapefiles]
print map_instance
>>>[1,1,1]
print sum(map_instance)
>>> 3
或者我可以这样做:
map_instance = Map.objects.filter(layers__in=shapefiles)
print map_instance.count()
>>>3
根据我的需要,map_instance 应该返回 1 个地图,因为只有一个地图实例包含 3 个 shapefile。我只是不知道如何使它工作......
【问题讨论】:
标签: django