Seenu S
Seenu S

Reputation: 3481

How to get multiple choices in Django without using ManyToManyField?

I need to create a field which can have multiple choices selected instead of one. These choices are fixed. For example:

we use CharField with choices option if we want one choice to be selected from multiple ones.

SEX_CHOICES = (('M', 'Male'),
               ('F', 'Female')
              )

class Model1(models.Model):
    name = models.CharField(max_length=30)
    sex = models.CharField(max_length=1, choices=SEX_CHOICES)

But I need similar setup for multiple choice. I don't want to use ManyToManyField as the choices will be fixed and not changing as time goes by.

Please guide.

Upvotes: 1

Views: 1806

Answers (4)

gkp
gkp

Reputation: 76

You have three basic choices:

  1. To use something like djangozone has suggested in his answer.
  2. Add a boolean field for each choice. You say the choices won't change. If they really don't change, why use a method that allows them to? This gives you a lot of advantages over method #1, ie you can index the choice fields.
  3. Use a many to many field. You say you don't want to do this but don't say why.

If they really don't change, I'd go with #2. Having a bunch of booleanfields is a good representation of a set of choices that don't change.

Upvotes: 2

argaen
argaen

Reputation: 4245

Check multiselect field package. It does what you want to and it works well (at least when I used it 4 months ago). You can also check https://pypi.python.org/pypi/django-select-multiple-field/ but I haven't tested it.

Upvotes: 1

Geo Jacob
Geo Jacob

Reputation: 6009

I think you searching for something like this

from django import forms


class Test(forms.Form):
    OPTIONS = (
        ("a", "A"),
        ("b", "B"),
        )
    name = forms.MultipleChoiceField(widget=forms.SelectMultiple,choices=OPTIONS)

Upvotes: 0

Odif Yltsaeb
Odif Yltsaeb

Reputation: 5656

To just have multipleselect you can add widget = forms.SelectMultiple as widget for that field in form.

But bigger problem is saving the selected stuff. For that you would have to write your own field, which is able to save the multiple choices into single CharField.

Check out this page: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/

Upvotes: 1

Related Questions