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

hrirmatl  于 2023-04-22  发布在  Go
关注(0)|答案(2)|浏览(131)

让我们假设我有下一个模型:

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'

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

owfi6suc

owfi6suc1#

这不是在a对象上注解的,而是在AB对象上注解的,所以:

for ab in b_obj.ab_set.all():
    print(ab.count_something)
koaltpgm

koaltpgm2#

您可以将"@property"添加到A模型,如

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

    @property
    def count_something(self):
        # do your count
        pass

然后再用你的方式

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

for a in a_qs:
    print(a.count_something)

相关问题