Django—给定查询集的相关ManyToManyField中的实例数

Django—给定查询集的相关ManyToManyField中的实例数,django,Django,我想知道有多少地图由一个ManyToManyField与一个queryset关联,或者用不同的方式说,有多少地图至少有一个shapefile作为层。 models.py: class Map(models.Model): layers = models.ManyToManyField(Shapefile) class Shapefile(models.Model): filename = models.CharField(max_length=255) views.py: s

我想知道有多少地图由一个ManyToManyField与一个queryset关联,或者用不同的方式说,有多少地图至少有一个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_实例应该返回1个map,因为只有一个map实例包含3个shapefile。我只是不知道如何让它工作

map_instances = shapefiles.count()
但为了更符合Django的风格,您可以为您的模型创建一个管理器:

class ShapefileManager(models.Manager):
    def map_instances(self, user):
        return self.filter(created_by=user).count()

class Shapefile(models.Model):
    filename = models.CharField(max_length=255)

    objects = ShapefileManager()

number = Shapefile.objects.map_instances(request.user)
编辑:很抱歉,您的问题回答错了。但我认为这个链接是你需要的,这是一个类似的问题:


  • 也许这就是你想要的:

    from django.db.models import Count
    
    maps_with_one_or_more_layer = Map.objects.all().annotate(Count('layers')).filter(layers__count__gte=1)
    
    how_many = maps_with_one_or_more_layers.count()
    

    医生:

    你好!我想计算与Shapefile相关的
    Map
    的数量,而不是Shapefile查询中的
    Shapefile
    实例的数量。我的编辑中的链接对你有帮助吗?这很接近,但并不完全是我想要的。。。参见编辑