Django database function - Window, expression argument

Hi!

I have a such an annotation.

toys = Toy.objects.filter(...).annotate(percent_rank=Window(expression=PercentRank(), order_by('price', 'id')).values_list('id', 'price', 'percent_rank').

The problem is percent_rank appears to be float rather than integer.
I want to integer percent like 45, 56, etc.
I tried
expression=round(PercentRank() * 100)

But it does not work this way.

Anyone familiar with this?

Thanks

It’s going to be a Func expression. You’re probably looking for something like:
toys = Toy.objects.filter(...).annotate(percent_rank=Window(expression=PercentRank(), order_by('price', 'id')).annotate(integer_rank=Round(F('percent_rank')*100)).values_list('id', 'price', 'integer_rank')

1 Like

That works, @KenWhitesell

But I am not sure if that is a good choice over doing in python in terms of performance.
What would you recommend?

For anything less than a million rows I don’t think you’re going to notice a difference.
Worrying about “performance” without knowing that you actually have a performance problem is a waste of time and effort.

There’s also not going to be a pat answer to that question - you’re going to get different answers based on hundreds of different factors. Any opinion outside of the specific context is pure conjecture, and what is found to be true in one context cannot be extrapolated as being true in a different context.

(Well, that and, if performance is that much of an issue, what are you doing using Python / Django for any of this?)

The rows will nearly reach a million for sure in the future.
We are now building an application which will be used by millions of users soon, so it’s critical for us to ensure that the code we write today will not be a bottleneck in the future.
That’s why I always do mind about performance.
We’re already noticing performance issues in other parts of application, so we are fixing those issues.
Anyway, my question was more about general situation and hearing from you, I think it’s okay to do it in SQL(database level).

Thanks