Multiple choice in model

Question:

ANIMALS = (('dog','dog'), ('cat','cat'))

class Owner(models.Model):
    animal = models.Charfield(choices=ANIMALS, max_length=10)

My problem is how I can do if I have both ?

Asked By: Coco

||

Answers:

your need to have model like this:

class Choices(models.Model):
  animal = models.CharField(max_length=20)

class Owner(models.Model):
    animal = models.ManyToManyField(Choices)
Answered By: Divya Prakash

Presumably your best solution is to think about how you are going to store the data at a database level. This will dictate your approach and therefore your solution.
You want a single column that stores multiple values so your best approach would be to use django-multiselectfield

from multiselectfield import MultiSelectField

MY_CHOICES = ((1, 'Item title 2.1'),
              (2, 'Item title 2.2'),
              (3, 'Item title 2.3'),
               (4, 'Item title 2.4'),
               (5, 'Item title 2.5'))

class MyModel(models.Model):
    my_field = MultiSelectField(choices=MY_CHOICES,
                                 max_choices=3,
                                 max_length=3)
Answered By: haduki
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.