Senči
Senči

Reputation: 941

How to Correctly implement a model which uses multiple choices?

I was wondering what is the correct way to implement multiple choices in django-models.

What I want to do: I want to have a set of choices (each is just a String) and save them somehow. Additionally it should be possible to choose none, one or multiple options.

I am pretty sure that django.choices is not the right thing to use here.

Is a ManyToManyField really the right thing to use and if so... how shall I implement it?

Regards and thanks in advance, Senad

Edit:

I've created a simple example. Would that be the right way to implement this?

class alert(models.Model):
  alertTime = models.DateTimeField('time when alert is triggered')
  daysOfWeek = models.ManyToManyField(day, blank=True, null=True)

class day(models.Model):
  name = models.CharField(max_length=100)

and then a fixture which fills "day" with all days of the week?

Upvotes: 0

Views: 219

Answers (1)

kdt
kdt

Reputation: 28489

You've kind of answered your own question. Field.choices is ruled out if you need to select multiple options. ManyToManyField works fine and has the advantage that you can change the choices without changing the code, if needed. You've already linked to the documentation for ManyToManyField, so just go ahead and follow that. You might also load the default choices using a fixture.

Upvotes: 1

Related Questions