开发者

how to use array in django

开发者 https://www.devze.com 2022-12-19 16:55 出处:网络
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

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 str开发者_如何学Going 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?


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()


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.


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/


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

0

精彩评论

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

关注公众号