Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

373
Vistas
Django rest framework - return objects ordered by callable method result

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!

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda