【问题标题】:Get list inside the annotate in django ORM在 django ORM 的注释中获取列表
【发布时间】:2025-12-07 00:25:02
【问题描述】:

我有 3 张桌子:-

 class Profile(models.Model):
       id = models.AutoField(primary_key=True)
       name = models.CharField()
       .....
       #some more field
       .....

class ProfileTestMapping(models.Model):
         id = models.AutoField(primary_key=True)
         profile = models.ForeignKey(Profile)
         test = models.ForeignKey(Test)
         .....
         #some more field
         ....

class Test(models.Model):
         id = models.AutoField(primary_key=True)
         name = models.CharField()
        .....
         #some more field
         ....

1 个人资料有许多测试。所以我想得到这样的数据:-

This is a raw array I am writing for the example purpose. 
profileList = [

    {
        profileName: 'any-name',
        ......
        otherProfileDetails
        .......
        testList: [
         {
            name: testName,
            id: 463743
         },
         {
            name: testName2,
            id: 463743
         }
        ]
     }
]

我正在使用annotate 获取与配置文件映射的测试的count,但没有获取与配置文件映射的测试详细信息。

更新:- 当前查询我得到的是计数但不是映射测试数据列表:-

Profile.objects.filter(isDisable=0).value('id', 'name').annotate(
  testCount = Count('profiletestmapping__test_id')
  testList = //Unable to get list of related data
)

【问题讨论】:

  • 发布您用来生成您提到的输出的查询。
  • @SachinKukreja 问题已更新。
  • @GAJESHPANIGRAHI 您不需要注释测试对象,因为它们已经在数据库中。您需要做的就是在获取 prefetch_related 的同时加入它们
  • @Ken4scholars 好的,我正在尝试。
  • @GAJESHPANIGRAHI 有用吗?如果有,请不要忘记投票并标记为答案

标签: python mysql django django-models orm


【解决方案1】:

您可以在选择个人资料时使用prefetch_related 加入所有测试。

Profile.objects.prefetch_related(
'ProfileTestMapping_set__test'
).all()

【讨论】:

  • @GAJESHPANIGRAHI 尝试我的建议并显示结果。当然,如果你喜欢,你可以用 count 来注释它