Django - How does order_by work?

I would like to know how Django order_by works if the given values ​​of the order_by fields are the same for the recordset. I have a score field in the database and I'm filtering the query with order_by('score') . How are records having the same values ​​for evaluation arranged?

Each time they are randomly ordered within a subset of records with an equal score, and this breaks the pagination on the client side. Is there a way to override this and return records in sequential order?

I am using Django 1.4 and PostgreSQL.

+4
source share
3 answers

order_by can have several parameters, I think order_by('score', '-create_time') will always return the same set of queries.

+9
source

As the other answers correctly explain, order_by() takes several arguments. I would suggest using something like:

 qs.order_by('score','pk') #where qs is your queryset 

I recommend using 'pk' (or '-pk' ) as the last argument in these cases, since each model has a pk field and its value will never be the same for 2 entries.

+10
source

If I understand correctly, I think that you need to constantly organize the result set every time, you can use something like order_by('score','id') , which will order first by account first, and then auto-increment id in score with the same values, therefore, your result is consistent. The documentation is here . You must be explicit in order_by if you want to get the correct set of results every time using "id" is one way.

+2
source

Source: https://habr.com/ru/post/1438347/


All Articles