Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use array in django

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?

like image 685
ha22109 Avatar asked Jun 08 '26 18:06

ha22109


2 Answers

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()
like image 66
Dominic Rodger Avatar answered Jun 11 '26 08:06

Dominic Rodger


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.

like image 44
Clueless Avatar answered Jun 11 '26 06:06

Clueless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!