For single-choices fields, we typically use CharField with the choices kwarg. Sometimes there are good reasons to make these foreign-keys to a lookup table, but hard-coded choices are typically easier and much faster to put together.
It would be nice if we could do the same with multiple-choice fields, in other words replacing many-to-many fields. What I'm thinking is:
CsvTextField model field
the choices API would fit the regular char/text/int field choices API
my_record.mycsvfield would return an array of choice strings, not the raw delimited string stored in the DB, and my_record.get_mycsvfield_display() would return comma-separated formatted choices
Delimeter is |. There shouldn't be need for custom delimeters because choices are stored as codes, not formatted strings
basic model (but not DB) validation: choices conform to delimited choices
(extra) Maybe an option to use a backing CharField if we want a character limit? (Defaulting to Textfield seems safer)
corresponding CsvField form field
default widget of multi-select or checkbox-select
The main advantages here are
ability to update choices without messing with the database
ability to upgrade an existing single-choice CharField to a multi-choice CharField
Much more productive for building stuff quickly
A few challenges I could think of are:
Subclassing fields and overriding (de-)serialization seems kind of complicated
The CSV field must contain at most one of each choice
Should it validate that all value exist in the choices list? Migrations could be difficult if we don't allow this. On the other hand it's asking for problems if we don't
Choices must be sorted in the same order all the time, otherwise we risk extraneous diffs
Not sure how we map our fields to custom form fields without using a modelform subclass (with its own custom metaclass 🤮 ), might just have to manually set the field on each form that uses this type of field
For single-choices fields, we typically use CharField with the
choices
kwarg. Sometimes there are good reasons to make these foreign-keys to a lookup table, but hard-coded choices are typically easier and much faster to put together.It would be nice if we could do the same with multiple-choice fields, in other words replacing many-to-many fields. What I'm thinking is:
CsvTextField
model fieldmy_record.mycsvfield
would return an array of choice strings, not the raw delimited string stored in the DB, andmy_record.get_mycsvfield_display()
would return comma-separated formatted choices|
. There shouldn't be need for custom delimeters because choices are stored as codes, not formatted stringsCsvField
form fieldThe main advantages here are
A few challenges I could think of are: