2

I'm new to Django and any help is appreciated, How can I restrict the choice option in one field based on a previous field. For example, if I select 'dog' for animal, I want to remove 'chocolate' from the FOOD_CHOICE, because I love dogs. Thanks!!!

ANIMAL_CHOICE = (
     ('a','cat'),
     ('b','dog'),
     ('c','fish'),
)
FOOD_CHOICE = (
      ('a', 'chocolate'),
      ('b', 'kittySnack'),
      ('c', 'steak'),
)


class Animal(models.Model):
    animal = models.CharField(max_length=1, choices= ANIMAL_CHOICE)
    food   = models.CharField(max_length=1, choices= FOOD_CHOICE)
Todor
  • 15,307
  • 5
  • 55
  • 62
Juan
  • 477
  • 4
  • 8

2 Answers2

0

you will do that from django forms, when youre cleaning the form, or you also can manipulate via javascript to remove that option from frontend

German Alzate
  • 801
  • 10
  • 19
0

You can't do this unless you write a set of rules, which is really complicated to maintain.
The best solution here is use a separate model for food, and add the foreign key to the animal model:

ANIMAL_CHOICE = (
     ('a','cat'),
     ('b','dog'),
     ('c','fish'),
)
FOOD_CHOICE = (
      ('a', 'chocolate'),
      ('b', 'kittySnack'),
      ('c', 'steak'),
)


class Animal(models.Model):
    animal = models.CharField(max_length=1, choices= ANIMAL_CHOICE)
    foods   = models.ManyToManyField(Food)

class Food(models.Model):
    food   = models.CharField(max_length=1, choices= FOOD_CHOICE)

On the other hand, you should guarantee that each animal entry are unique, the same for each food record. This will avoid duplicates.
Now, using choices here, limits the solution and make it hard coded, this will require change your code if you want to include a new animal or new food.

Suggestion

class Animal(models.Model):
        name = models.CharField(max_length=50, unique=True)
        description = models.TextField()
        foods   = models.ManyToManyField(Food)

class Food(models.Model):
        name   = models.CharField(max_length=50, unique=True)
        description = models.TextField()
Yasel
  • 2,920
  • 4
  • 40
  • 48