【问题标题】:Django - Number of instance in a related ManyToManyField for a given querysetDjango - 给定查询集的相关 ManyToManyField 中的实例数
【发布时间】: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


    【解决方案1】:

    也许这就是你要找的东西:

    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()
    

    文档:QuerySet API reference - Annotate

    【讨论】:

      【解决方案2】:
      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)
      

      编辑:抱歉,误解了你的问题。但我认为这个链接是你需要的,这是一个类似的问题:

      1. count values from manytomanyfield

      2. How to count and display objects in relation ManyToMany in Django

      【讨论】:

      • 嗨!我想计算与 shapefile 相关的 Map 的数量,而不是 shapefile 查询集中的 Shapefile 实例的数量
      • 抱歉,误解了您的问题。我的编辑中的链接对您有帮助吗?
      • 这很接近,但不完全是我正在寻找的...查看编辑
      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多