Django multi select multiple choice model field

To me, it doesn’t really make sense to store static data in a database – especially if there are only 5 or 6 errr datum you are wanting to store. Django allows you to use a Charfield with choices, i.e.

WIND = 'W'
SOLAR = 'S'
ENERGY_TYPE_CHOICES = (
    (WIND, 'Wind turbine'),
    (SOLAR, 'Solar panels')
)
energy_type = models.CharField(max_length=1, choices=ENERGY_TYPE_CHOICES, default=WIND)

But unfortunately you can’t select multiple choices, so in this case it wouldn’t be possible to associate both wind & solar with one of my models. It is suggested that developers store this info in a separate table and associate the choices with models using a manytomanyfield. Perhaps this makes sense if you want to associate the field options with multiple models, but it really seems overkill if you just want to have multiple choices for a single model.

Strangely there don’t seem to be many other people who have felt this to be too much (I mean, going by google anyway). As I have frequently found with Django, a few people have discussed it on stackoverflow and there are a million ways of doing the same thing with no clear indiciation as to which is most widely used and most sensible. Well, there are 3 different modules/alternatives:

  • Multiselectfield: https://github.com/goinnn/django-multiselectfield
  • Multiple_select_field: https://gist.github.com/kottenator/9a50e4207cff15c03f8e
  • Select_multiple_field: https://github.com/kelvinwong-ca/django-select-multiple-field

This is ridiculous. Django’s “do-it-yourself” attitude is refreshing after coming from PHP and Drupal, but why isn’t something this ubiquitous integrated into Django itself?  This is something many projects are going to want. Or do I have it wrong and is it better to have a separate db table for like 2 or 3 fields?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>