【问题标题】:django many to many querysetdjango 多对多查询集
【发布时间】:2021-11-14 23:50:04
【问题描述】:

我有两个模型:

1-----

class Account(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=150)
    phone = models.CharField(max_length=50)
    picture = models.ImageField(blank=True, null=True , upload_to='profile' )
    profession = models.ManyToManyField(Profession)

2-----

class Profession(models.Model):
    profession = models.CharField(max_length=50)

我想展示我拥有的所有职业 同时我想显示他们拥有该专业的帐户数量

喜欢这张照片 enter image description here

【问题讨论】:

    标签: python django django-models django-queryset


    【解决方案1】:

    您可以像这样注释每个职业名称:

    Profession.objects.values('profession').annotate(num_accounts=Count('account'))
    

    这将为您提供如下输出:

    <ProfessionQuerySet [{'profession': 'SomeProfessionA', 'num_accounts': 22}, {'profession': 'SomeProfessionB', 'num_accounts': 20}, ...>
    

    【讨论】:

    • oooooooooo broo 非常感谢你,但是你怎么知道的???这是我想要的工作
    猜你喜欢
    • 2014-04-04
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2022-01-18
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多