Home > Blockchain >  Multiple choice in model
Multiple choice in model

Time:12-02

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 ?

CodePudding user response:

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)

CodePudding user response:

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)
  • Related