[Django]-Store django forms.MultipleChoiceField in Models directly

11đź‘Ť

âś…

The first thing I would consider is better normalization of your database schema; if a single instance of your model can have multiple values for this field, the field perhaps should be a linked model with a ForeignKey instead.

If you’re using Postgres, you could also use an ARRAY field; Django now has built-in support.

If you can’t do either of those, then you do basically need to reimplement a (better) version of CommaSeparatedIntegerField. The reason is that CommaSeparatedIntegerField is nothing but a plain CharField whose default formfield representation is a regex-validated text input. In other words, it doesn’t do anything that’s useful to you.

What you need to write is a custom ListField or MultipleValuesField that expects a Python list and returns a Python list, but internally converts that list to/from a comma-separated string for insertion in the database. Read the documentation on custom model fields; I think in your case you’ll want a subclass of CharField with two methods overridden: to_python (convert CSV string to Python list) and get_db_prep_value (convert Python list to CSV string).

👤Carl Meyer

1đź‘Ť

I just had this same problem and the solution (to me) because as Carl Meyer put it. I don’t want a normalized version of this “list of strings” is to just have a CharField in the model. This way your model will store the normalized list of items. In my case this is countries.

So the model declaration is just

countries = CharField(max_lenght=XXX) 

where XXX is a precalculated value of 2x my country list. Because it’s simpler for us to apply a check to see if the current country is in this list rather than do it as a M2M to a Country table.

👤Jorge Vargas

Leave a comment