与 Queryset.annotate() 混淆

Confusion with Queryset.annotate()

我有两个模型:

class Property(models.Model):
    # code here...

class AccommodationType(models.Model):
    property = models.ForeignKey(Property, related_name='accommodation_types')
    # rest of code here...

我想要做的是用相关 AccommodationType 的计数来注释 属性 的查询集,并按此计数的值对其进行过滤。所以这是我的代码:

qs = Property.objects.all()
qs.annotate(acc_types_count=Count('accommodation_types'))
filtered = qs.filter(acc_types_count=1)

这里我得到了错误:

django.core.exceptions.FieldError: Cannot resolve keyword 'acc_types_count' into field. Choices are:  # ...rest of the fields

我哪里错了?

annotate,与 filter 一样,不会改变查询集,而是 returns 一个新的。您需要将其重新分配给 qs:

qs.annotate(acc_types_count=Count('accommodation_types'))

或结合原查询:

qs = Property.objects.all().annotate(acc_types_count=Count('accommodation_types'))