我正在使用django 1.11:
型号:
class Model(models.Model):
.
.
.
def count_total(self):
return self.anothermodel_set.filter(val=False).count()
查看:
class ModelViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Model.objects.all()
serializer_class = ModelSerializerClass
permissions = AuthenticatedReadOnly
pagination_class = StandardResultsSetPagination
def list(self, request):
queryset = Model.objects.all()
# Attempt 1: returns wrong count
queryset = queryset.annotate(a_count=Count(Case(When(anothermodel__val=False, then=1), default=0, output_field=IntegerField())))
# Attempt 2: returns wrong count, same as attempt 1
queryset = queryset.annotate(b_count=Count(Q(anothermodel__val=False)))
# ideally I want to do
queryset = queryset.order_by('count_total')
当我按count_total
排序时,我会给出
FieldError at /api/endpoint/ Cannot resolve keyword 'count_total' into field.
序列化程序:
在我的序列化程序中,我修改了要调试的to_represantation
定义:
def to_representation(self, instance):
return {'id': instance.pk, 'a_count': instance.a_count, 'b_count' : instance.b_count, 'correct_count': instance.count_total()}
否则,在我的序列化程序中,我有:
class Meta:
model = Model
fields = ('id', 'title', 'bunch-of-other-stuff', 'count_total')
instance.count_total()
返回正确的结果,但我不能简单地将其用作视图中的queryset.order_by('count_total')
,以便在没有注释的情况下对结果进行排序。你知道吗
有什么问题吗?你知道吗
我不确定这是不是你的问题,但模型定义似乎没有使用,因为你没有返回一个值,只是做计算。应该是:
我也不明白为什么在模型和视图中都要进行计算。可以使用模型定义,也可以对查询集进行注释,但不需要同时进行这两种操作。如果选择“模型定义”路线,则视图应如下所示:
如果使用模型定义,则需要在序列化程序中设置只读属性:
如果仍然出现“unable to resolve count total into field”错误,请在运行序列化程序之前向视图集中抛出一条print语句,如下所示:
问题可能在于如何过滤模型定义。你知道吗
相关问题 更多 >
编程相关推荐