【问题标题】:How to count occurrences in Django query and return list with attribute如何计算 Django 查询中的出现次数并返回带有属性的列表
【发布时间】:2020-04-06 12:13:19
【问题描述】:

我想运行一个查询,并返回一个包含唯一对象名称及其频率的列表。我遇到了一些解释这一点的帖子,但似乎无法资助使用对象名称属性的帖子。例如:

powderList = Build.objects.values('powder').annotate(total_count=Count('powder')).order_by('total_count')

返回:

{'powder': None, 'total_count': 0}, {'powder': 1, 'total_count': 2}, {'powder': 2, 'total_count': 2}

这与我想要的非常接近,但是这显示了powderid。我想访问粉末的属性(powder.name),以便它输出:

{'powder': None, 'total_count': 0}, {'powder': Titanium, 'total_count': 2}, {'powder': Steel, 'total_count': 2}

我试过了:

powderList = Build.objects.values('powder.name').annotate(total_count=Count('powder')).order_by('total_count')

powderList = Build.objects.values('powder').annotate(total_count=Count('powder.name')).order_by('total_count')

我的下一个计划是使用for loop 遍历字典并使用 id 查找名称,但这每次都会访问数据库。有没有更有效的正确方法来做到这一点?

我的模型如下所示:

class Build(models.Model): #(DMLS)
    PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    plannedAuthor =  models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE)
    powder =  models.ForeignKey('Powder', null=True, blank=True, on_delete=models.CASCADE)


class Powder(models.Model):
    PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    name = models.CharField(max_length=50,)

【问题讨论】:

    标签: django


    【解决方案1】:

    你试过了吗,

    powderList = Build.objects.<b>values('powder__name')</b>.annotate(total_count=Count('powder')).order_by('total_count')

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      相关资源
      最近更新 更多