Django ORM - 如何访问带注释的字段值?

问题描述 投票:0回答:0

假设我有下一个模型:

class A(model):
    b = models.ManyToManyField("b", through="AB")

class B(model):
    id = models.CharField()

class AB(model):
     a = models.ForeignKey("a")
     b = models.ForeignKey("b")

我想为特定的 B 对象检索所有相关的 A 对象,并为每个 A 对象加上注释字段

count_something

b_obj = B.objects.prefetch_related(Prefetch('ab_set',  
                                   queryset=AB.objects.select_related('a')
                                              .annotate(count_something = Count(....))))
                .get(id=<b_id>)

我试过这个方法,但是不行

a_qs = [ab.a for ab in b_obj.ab_set.all()]

for a in a_qs:
    print(a.count_something)

错误:

 "A" object has no attribute 'count_something'

实现我想要的正确方法是什么?

django django-models django-rest-framework django-orm
© www.soinside.com 2019 - 2024. All rights reserved.