Ad

Django Model Limit Choices Based On Another Model But With A Specific Field Value

- 1 answer

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.ForeignKey(Category)

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.

EDIT: Changed to models.ForeignKey.

Ad

Answer

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 dynamiclaly depending of wich 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

Ad
source: stackoverflow.com
Ad