开发者

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 CommaSeparatedI开发者_运维知识库ntegerField, 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...


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]


The only difference between this field type and a CharField is that it validates that the data is in the proper format - only digits separated by ','. You can view the source for the class at http://docs.nullpobug.com/django/trunk/django.db.models.fields-pysrc.html#CommaSeparatedIntegerField (expand the '+').

You can turn such a string into an actual Python list value (not array - list is the proper term for Python) by using eval.

>>> eval("[1,2,3,4]")
[1, 2, 3, 4]

EDIT: eval has safety concerns, however and a better method is to use literal_eval as suggest by Alvin in another answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜