I want to store a list of integers as a field in my model. As there is no field provided for this by default in Django, I am doing it by using a CommaSeparatedIntegerField called x
. In my view, I then take this string and create a list of integers from it. When a model instance is created with parameter n
, I want x
to be set to length n
, with each element being set to zero.
Here's the model:
class Foo(models.Model):
id = models.IntegerField(default = 0)
x = models.CommaSeparatedIntegerField(max_length = 10)
@classmethod
def create(cls, _id, n):
user = cls(id = _id)
user.class_num_shown = '0,' * n
Then I create an instance:
f = Foo.create(1, 4)
f.save()
And load it from the database and convert the string into a list:
f = Foo.objects.get(id = 1)
x_string = f.x
x_list = x_string.split(',')
print x_list
But this outputs [u'0,0,0,0,']
rather than what I want, which would be [0,0,0,0]
. How can I achieve my desired output?