enchance
enchance

Reputation: 30411

Django model limit choices based on another model but with a specific field value

I have got 2 models, simplified for this question. In the Article model, how can I limit the choices= of the field Article.status based on the entries in the Category model which have a specific Category.type value?

class Article(models.Model):
  name = models.CharField(max_length=100)
  # Set choices= only to values of Category which have a type of 'foo'
  status = models.CharField(max_length=10, choices=)

class Category(models.Model):
  name = models.CharField(max_length=10)
  type = models.CharField(max_length=10)

For transparency, I know I've done this before but I can't seem to remember how or find the project where I did it. It's like the solution just disappeared on me...*poof*. Magic.

Upvotes: 4

Views: 2256

Answers (1)

Ben Boyer
Ben Boyer

Reputation: 1234

You can use something like limit_choices_to in your models.py :

category = model.ForeignKey(Category,limit_choices_to={'type':'the type you want'}

If you want something more dynamic, or more detailed, you can specify your custom queryset of a specific field in the init of a ModelForm like :

self.fields['category'].queryset = Category.objects.filter(type='type_you_wanted')

If you want to display the category dynamically depending of which category.type are selected in the form then you should see this: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Upvotes: 7

Related Questions