Home > Software design >  Django setup model with multi value integer field
Django setup model with multi value integer field

Time:05-25

How can we setup a field in a model to accept more than on value? We simply can make relation fields using foreign key or many to many but in case of simple int or float or any simple variable type , how can we achieve multi value field?

CodePudding user response:

If it is only about the database field, you could simply serialize your values into a string, e.g. values 1, 2, 3 become "1,2,3" in the field. Simply overwrite the getter and setter for that field (using @property), to serialize and unserialize the values each time the field is accessed.

CodePudding user response:

Another approach is to use a JSONField (doc). This has wider support (for example searchability via querysets, at least using PostGreSQL. Also several 3rd party JSON form fields. You'd need to validate that the JSON supplied was a list of integers).

  • Related