I would like to know how many maps are related by a ManyToManyField to a queryset, or said differently, how many maps have at least one of the shapefiles as layer.
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... ???
example:
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
or alternatively I could do:
map_instance = Map.objects.filter(layers__in=shapefiles)
print map_instance.count()
>>>3
for my needs, the map_instance should return 1 map because there is only one map instance that contains the 3 shapefiles. I just dont get how to make it works...