3

I'm seeing weird outputs while trying to order_by booleanfield in postgresql.

I have a boolean field with default=false and I'm using the order_by(-thebooleanfield) and something I see the True value first which is what I expected but something the False values come first.

Do I need to switch to different type? Or there is a correct way to order_by booleanfield in postgresql?

10x

1 Answer 1

1

Django is ordering by the value stored in the underlying database. I've never found any official explanation in the Django documentation, but there was a Django ticket a while back that explains it:

https://code.djangoproject.com/ticket/19726

Basically, the devs marked it as wontfix because implementing a consistent behaviour between database backends would make them more fragile.

The best way to ensure consistent behaviour is probably to sort the values client-side.

Sign up to request clarification or add additional context in comments.

3 Comments

sorting in client side is not an option, what about using an small integer field with 0/1?
as I understand the default=False is taking care of in Django layer and not the DB layer, maybe I should explicitly set the value to False when saving the model to the DB.
I suppose that would work, though you would likely want to make sure the form field widget is a checkbox and not a text input. Perhaps you could add some logic in your views to check the first sorted item's boolean value and reverse it if it's not what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.