-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Fix ordering duplication on non-unique field #9109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix ordering duplication on non-unique field #9109
Conversation
Co-authored-by: Roman Gorbil <roman.gorbil@saritasa.com>
4b4143d
to
e16f385
Compare
I'm not entirely convinced that this is desired behavior. Yes, the ordering without If anything, I'd be more in favor of calling this out in the ordering documentation as something people should be aware of in case of equal ordering. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not entirely convinced that this is desired behavior. Yes, the ordering without pk is unexpected but arguably what's worse is not being able to rely on the ordering that you set in a view is the ordering that you get on the queryset level.
If anything, I'd be more in favor of calling this out in the ordering documentation as something people should be aware of in case of equal ordering.
-- From Kevin Brown's review
So how should this one be fixed outside drf? Tell front-end to always add |
This very much so depends on who is the consumer of your API and if your API is new or existing. Let's walk through the options given by you.
This is the standard move in APIs that are already existing. You don't necessarily tell them to add
If you're the only consumer, you can break your contract, or you're working with a brand new API, this is probably the way to go. The challenge here is that DRF expects that ordering fields will be unique or nearly unique. And for cases where this matters a lot, such as for cursor pagination, DRF tries to detect the common cases where this goes wrong (double underscore ordering fields) and raise a warning about it. But in most cases the uniqueness of the ordering is critical so DRF leans towards flexibility instead. |
closing as per design decision by maintainers as not needed |
Description
Always add "pk" as last parameter for ordering.
For example, we have following QS
And we want to order it by name and take 2nd element.
We can get following results:
qs.order_by('name')
Or we can get:
As you see, QS is correctly ordered, but order is not consistent, and
pagination is also inconsistent since we are using fields which doesn't
have unique restriction. So we always add "pk" as last ordering param.
Unfornualy I couldn't reproduce this behavior for tests, might be the is that in tests sqlite in memory is used. But on postgress result is stable. Here is an example: