我有两个模型:
class Property(models.Model):
# code here...
class AccommodationType(models.Model):
property = models.ForeignKey(Property, related_name='accommodation_types')
# rest of code here...我要尝试的是用相关的AccommodationType的计数来注释属性的queryset,并根据这个计数的值对其进行过滤。下面是我的代码:
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我哪里错了?
发布于 2017-06-21 05:32:53
与filter一样,annotate不会改变查询集,但会返回一个新的查询集。您需要将其重新分配给qs
qs.annotate(acc_types_count=Count('accommodation_types'))或者将其与原始查询相结合:
qs = Property.objects.all().annotate(acc_types_count=Count('accommodation_types'))https://stackoverflow.com/questions/44662981
复制相似问题