Brian
Brian

Reputation: 13

Dynamic choice fields in Django

Referencing the Django docs on this, I have set up the following:

Category_Choices = (
    ('Food', (
        ('burger', 'hamburger'),
        ('pizza', 'pizza'),
        ),
    ('Drink', (
        ('soda', 'soda'),
        ('water', 'water'),
        ('milk', 'milk'),
        ('beer', 'beer'),
        ),
    ('Dessert' , (
        ('ic', 'ice cream'),
        ('pie', 'pie'),
        ('cake', 'cake'),
        ),
)

I understand referencing an initial tuple:

choice = models.CharField(max_length=10, choices=Category_Choices)

But how do I limit that to just Food? If I have one choice list where a user selects only Food, Drink, or Dessert, how do I limit a second choice list to only Food item, or only drink items, etc? The Django docs don't cover that part. Thanks in advance

Upvotes: 1

Views: 304

Answers (1)

waldol1
waldol1

Reputation: 1881

Examining the linked documentation yields this response:

"But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever."

The choices field is not intended to give dynamic behavior, ie display only certain subsets of choices.

My suggestion would be to create another model object to accommodate just the Food list.

Upvotes: 1

Related Questions