django - 姜戈休息。按计算模型字段排序
问题描述
我坚持在计算字段上排序。
假设我的模型看起来像:
class Foo(models.Model):
fieldA = models.CharField()
fieldB = models.CharField()
@property
def calculatedField(self):
return someFunc(fieldA)
现在我ViewSet
不能将订单应用到calculatedField
,所以我有以下代码:
class SomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
...
ordering_fields = ('calculatedField',)
...
但是当我尝试使用查询参数申请订单时
Method GET /someEndpoint/?ordering=calculatedField
我收到以下错误
Cannot resolve keyword 'calculatedField' into the field. Choices are: ...
有没有办法将订单申请到计算字段?谢谢
解决方案
你必须注释额外的字段
class SomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
...
ordering_fields = ('calculatedField',)
def get_queryset(self):
return self.queryset.annotate(other function)