Building a user defined ordering for REST API content


I am fairly new to Django so I apologize if this is an obvious question.

I have a Django project that processes some external data and makes it available via the Django REST Framework. My database is PostgreSQL.

I allow admin users to create a set of “questions” to be published. I have been asked to allow the admin users to set a custom order to the published questions.

I am not really sure how best to do this in Django. The “questions” are defined in a model and have relationships to a number of other models.

I could add a field called “rank” but I would like my users to select an object’s rank without having to re-order the other object’s in the model/table.

I could also implement this by creating some form of data structure like a list, which is stored elsewhere in the database and then have some custom code move items around in the list whenever an admin changes the rank. Though this seems rather hacky.

Is there some more straightforward way of doing something like this in Django? A self-ordering unique constraint on the model would be awesome… Especially one that would easily be implemented through the crud so admin users could change an object’s rank easily and have all the others re-order in response.

Ultimately I would like to publish the “rank” field via the API so consumers can order in the front end however they wish. Ordering of the serializer output would also be acceptable.

In addition to the two ideas that you’ve identified here, you can also take advantage of the PostgreSQL ArrayField to store a list of the PKs in the desired order. That way, you don’t need to maintain any ordinal numbering of the elements. You can also arbitrarily add and remove elements in addition to just resequencing them.

Would that mean having a single row model somewhere else in the database that just stored the PKs of the Question model or is there a better way to store that?

Additionally, what would be the best way to communicate that to the API? Would I be generating my serializer from that list and exposing entries only in that order?

I guess I could pass the index of the PKs via the serializer to the REST output?

That’s probably the easiest way to do it. However, I got the impression (perhaps incorrectly) that there might be multiple such lists being stored with different orderings by different people, so it wouldn’t be a “single-row model” It could be a seperate set of rows - one per user per set of questions.

That’s entirely up to you. Use it for however you want. The only limit is your imagination.

At this stage no, it would be a single ordering for the publicly exposed REST API.

If it’s not a big performance hit allowing for multiple sets of orders might be of use in the future.