Django-用ManytoMany关系计数来注释(重新引用)

时间:2019-11-16 20:08:44

标签: django django-annotate

Django - Annotate with count across ManytoMany relationships

我无法找到一种使用多对多关系中的元素使用次数计数来注释查询集的方法。

class Profile(models.Model):
    [...]
    # Profile can have multiple roles
    roles = models.ManyToManyField('Role', blank=True)
    [...]

class Role(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    name = models.CharField(blank=True, max_length=30)
    description = models.CharField(blank=True, max_length=300)
    [...] 

例如,我将担任5个角色:

  • 角色1
  • 角色2
  • 角色3
  • 角色4
  • 角色5

以及分配了以下角色的2个配置文件:

  • 个人资料1
    • 角色1
    • 角色2
  • 个人资料2
    • 角色1
    • 角色3
    • 角色4

我需要与@ ha-duy相反:

Profile: name, role_count=2
Profile: name, role_count=3

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

一个主意:

在同一视图中,您通过许多字段更新滚动循环并返回长度。然后适当地更新模型。

更好的主意:

为配置文件模型创建一个自定义保存方法,以便每次调用.save()时,它将计算角色数并更新该字段。 有关此的更多信息。 custom save method on model - django

也许这会有所帮助,因为它不会在数据库中持久存在,但会为您提供信息:

class Test(models.Model):
name = models.CharField(max_length=10,)
category = models.ManyToManyField(cats)

def __str__(self):
    x = self.category.all()
    y = len(x) 
    return 'this is an item count ' + str(y)

,或者如果您希望以对象形式使用它:

将此添加到模型中。

    def dataBlock(self):
       x = self.category.all()
       y = len(x) 
       return {
           'name': self.name,
           'cat_length': y,
       }