python - Django: Using expressions on related fields in extra or order_by -
i need calculate , order expression in django. what's efficient way this?
example setup:
class rating(models.model): rating = models.integerfield(...) prev = models.foreignkey('rating')
i have calculate difference of current rating , previous , order it. have few methods work.
method 1: use extra()
add select clause calculates diff. depends on way django labels joined tables in sql query. example:
rating.objects.filter(prev__isnull=false)\ .select_related('prev')\ .extra(select={'diff': 'rating.rating - t3.rating'})\ .order_by('-diff')
(in case joined table named t3
since have second related field in model)
method 2: add field model.
method 3: sorting in python. inefficient.
what i'd like: being able use f
expressions in select
clause, so:
rating.objects.filter(prev__isnull=false)\ .extra(select={'diff': f('rating') - f('prev__rating')})\ .order_by('-diff')
or possibly in order by
clause:
rating.objects.filter(prev__isnull=false)\ .order_by(f('rating') - f('prev__rating'))
this perhaps question better asked django devs want see ideas have.
Comments
Post a Comment