2

I am stuck with ordering on calculated field.

Let's say my model looks like:

class Foo(models.Model):
    fieldA = models.CharField()
    fieldB = models.CharField()

    @property
    def calculatedField(self):
        return someFunc(fieldA)

Now I wan't my ViewSet to be able to apply ordering to calculatedField, so I have following code in there:

class SomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    ...
    ordering_fields = ('calculatedField',)
    ...

But when I try to apply to order using query parameters like

Method GET /someEndpoint/?ordering=calculatedField

I get the following error

Cannot resolve keyword 'calculatedField' into the field. Choices are: ...

Is there a way to apply to order to calculatedField? Thanks

Rarblack
  • 4,559
  • 4
  • 22
  • 33
Novikas
  • 21
  • 2
  • https://stackoverflow.com/questions/2168475/django-admin-how-to-sort-by-one-of-the-custom-list-display-fields-that-has-no-d – Josef Korbel Oct 15 '18 at 10:13

1 Answers1

0

you have to annotate the extra field

class SomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
...
ordering_fields = ('calculatedField',)

def get_queryset(self):
   return self.queryset.annotate(other function)
aman kumar
  • 3,086
  • 1
  • 17
  • 24
  • I have tried like this: ```self.queryset.annotate(other_function(F('one_of_the_fields_on_model')))```, but it turned out exceptions cause ```F('one_of_the_fields_on_model')``` is not an actual value. How should I do? – Gorgine Oct 22 '20 at 06:36
  • This answer is not helpful at all. – Michael Sep 28 '21 at 00:49