So basically the title says it all: how can I order the queryset that will be returned on the API by a callable method result that is not stored on the database?
This field is dynamic and depends on each user's request, hence it can't be stored anywhere.
I tried just using, which is what I want to achieve:
queryset = Post.objects.filter('my_filters').order_by('my_method')
but it doesn't work since it has to be a column on the database.
I also tried:
queryset = sorted(Post.objects.filter('my_filters'), key=lambda x: x.my_method())
But it throws the "AttributeError: 'list' object has no attribute 'model'" error.
How can I sort the results of the queryset according to a method then? Any ideas? I will also need to limit the number of responses to the top results calculated this way.
Thanks!
EDIT:
'my_filters' in this case just checks a boolean property
.filter(active=True)
and my_method checks the time elapsed comparing with timezone.now():
def microseconds_elapsed(self):
return getMicrosecondsElapsed(self.datetime)
where
def getMicrosecondsElapsed(datetime):
timedelta = timezone.now() - datetime
microseconds = 0
microseconds += timedelta.microseconds
microseconds += timedelta.seconds*1000000
microseconds += timedelta.days*86400000000
return microseconds
I've made some progress using annotate and PostgreSQL functions by using:
get_queryset().annotate(time_elapsed=Func(F('datetime'), function='age'))
but this results in a django error
float() argument must be a string or a number
In this case I just need to get the number of microseconds elapsed from the datetime field stored in the object so I can proceed with another calculation.
Anybody knows what's going on and how can I achieve this?
Thanks!