views:

815

answers:

1

Say I have choices defined as follows:

choices = (('1','a'),
           ('2','b'),
           ('3','c'))

And a form that renders and inputs these values in a MultipleChoiceField,

class Form1(forms.Form):
    field = forms.MultipleChoiceField(choices=choices)

What is the right way to store field in a model.

I can of course loop through the forms.cleaned_data['field'] and obtain a value that fits in models.CommaSeperatedIntegerField.

Again, each time I retrieve these values, I will have to loop and convert into options.

I think there is a better way to do so, as in this way, I am in a way re-implementing the function that CommaSeperateIntegerField is supposed to do.

+2  A: 

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 have good reason not to do that, 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