2

I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error

int() argument must be a string or a number, not 'list

How can I add this field to my model? I am using this field in my views.py so I need to add it in my model. Any suggestions?

1
  • What is the datatype in your database? What database are you using? Commented Feb 4, 2010 at 7:24

4 Answers 4

7

You may be interested in using a CommaSeparatedIntegerField.

If you've got a list of integers like this:

my_ints = [1,2,3,4,5]

and a model like this:

class MyModel(models.Model):
    values = CommaSeparatedIntegerField(max_length = 200)

then you can save my_ints into a MyModel like this:

m = MyModel(values = ','.join(my_ints))
m.save()
Sign up to request clarification or add additional context in comments.

Comments

1

I would look into database normalization. In particular, your database is not even in 1st normal form, the first and probably most significant of the normal forms which states that normalized data should not contain any repeating groups. As a result, the Django object-relational-mapper will have considerable difficulty modeling your data.

By supporting only single, non-repeating types, Django in a sense enforces 1st normal form in data. You could try to write your own SQL to manage this particular field or perhaps find some code on the internet, but perhaps better would be to refactor this field into a many-to-one relationship in its own model. You can find Django documentation on this here.

Comments

1

Clueless' answer is probably the best you can get, but in case you still want to store array of numbers in single field, you can do this - either by manually e.g. pickling it and then storing to TextField, or by writing custom model field that do something like this for you automatically.

Here's the doc: http://docs.djangoproject.com/en/1.1/howto/custom-model-fields/

Comments

1

I got it working by saying textfield in my model.Since i am only using that field for reading it doesnot effect me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.