How to order a filtered django query set by a decimal field

Viewed 351

I am trying to sort my query set by a "ranking value" which I have as a decimal field in my django model, however it seems the "order_by" function doesn't seem to work? my query set is always the same, with no ordering.

I have tried the google but come up short, am I missing something here?

2 Answers

This happens because DecimalField is stored as a string when indexing.

Let'suppose you have

class My_model(models.Model):

    n_decimals = 2

    ...

    decimal_field = models.DecimalField(max_digits=10, decimal_places=n_decimals)

    def temp_int_field(self, obj):
        return int ( float(obj.decimal_field) * (10**n_decimals) )  # please notice that the exponent of 10 is equal to the number of decimal_places

Try to do the order_by like this:

query_set = My_model.objects.all().order_by('temp_int_field')

I need to see your code, but without looking i can ask you to use the "round(x)" function (where x is a float) on all your values, it will not change the ranking (mathematically sure about this), and order_by will work

Would love to see your code indeed !

Tip : Use a for loop to round all the numbers or make a function

Related