【发布时间】: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}
这与我想要的非常接近,但是这显示了powder 的id。我想访问粉末的属性(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