Django change ordering of items in a Postgres ArrayField

Viewed 278
dm_scripts = ArrayField(models.TextField(blank=True, null=True), default=list)

I have a Django model, and I wanted to use the ArrayField to store a list of TextFiles. The order matters, and I've been asked to allow a user to reorder these. How would you do that?

I've googled and searched here, but found nothing. Even Django's official documentation doesn't mention this.

1 Answers

I know this question is old, but I was looking for an answer, found one and thought I'd post the solution in case it is useful to others

A Django Postgres ArrayField is basically a list (at least in your case), so once you access it like object.dm_scripts you can manipulate it like any other list. For example, if you need to sort something alphabetically, you can call:

ordered_array = sorted(object.dm_scripts)
ordered_array.save()

Afterwards the list items will stay in that order. You can call that and apply it anywhere necessary, in a view, a def save method or whatever.

After that it's up to your imagination. Implementation would really depend on the UX interaction. I think it would be easy to pass the list to a javascript front-end, have the user reorder them visually, then apply the new order to the list items (Or many surely more optimised methods).

Related