0

I have a table containing a string field with a value like the following: '["value1", "value3", "value2"]'. Using the Django ORM, I require to convert that string type value to a list containing the values sorted alphabetically. It is necessary to keep the data type as string but to store a list inside it. So far I managed to convert it to a list but I can't sort the data.

.annotate(
    my_field=Cast('field', output_field=JSONField()),
)
Alonso
  • 1
  • Why not sort it in Django itself, instead of the database? – Willem Van Onsem Dec 12 '22 at 17:37
  • Running the query and then through a for loop sorting each of the fields manually? I prefer not to do it this way because I noticed that when you make modifications directly from the query the processing speed is much faster than when you use a for loop to modify each piece of data. I understand that you mean to do something similar to this: query = Model.objects.all() for item in query: query['field'] = eval(query['field']).sort() – Alonso Dec 12 '22 at 17:43
  • not with `eval`, that is unsafe and just pure evil. But it looks like you have some `ManyToManyField` encoded as a JSON blob, which is not a good modeling (for a relational database). – Willem Van Onsem Dec 12 '22 at 17:45
  • Yes, I preferred to store that field in another way to make it more comfortable to work with, but they tell me that it is necessary to keep the field as we currently have it. – Alonso Dec 12 '22 at 17:51
  • Please provide enough code so others can better understand or reproduce the problem. – Community Dec 16 '22 at 08:50

0 Answers0