Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an array of integers with Django

I've been trying to store an array of integers in a field of a Django model. Based on this reply, I've been trying to do so using a CommaSeparatedIntegerField, however this has proved less intuitive than the name would imply.

If I have a comma-separated list of integers (list = [12,23,31]), and I store it in a CommaSeparatedIntegerField, it comes back as a string (retrieved_list outputs u'[1,2,3]'). I cannot simply retrieve my integers : for instance, int(retrieved_list[1]) outputs 1 whereas list[1] would output 23.

So, do I have to do the parsing by hand, or is there any other solution? And how exactly does a CommaSeparatedIntegerField differs from a CharField? Seems to me like they behave pretty much the same...

like image 624
storm Avatar asked Jun 06 '11 05:06

storm


1 Answers

Eval was accepted as answer above -- avoid the temptation it's just not safe

See: Python: make eval safe

There is a literal_eval function that could be used the same way:

>>> from ast import literal_eval
>>> literal_eval("[1,2,3,4]")
[1, 2, 3, 4]
like image 180
Alvin Avatar answered Oct 28 '22 10:10

Alvin