Django 模型限制基于另一个模型但具有特定字段值的选择

enc*_*nce 2 python django django-models

我有 2 个模型,针对这个问题进行了简化。在Article模型中,如何根据模型中具有特定值的条目限制choices=字段?Article.statusCategoryCategory.type

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)
Run Code Online (Sandbox Code Playgroud)

为透明起见,我知道我以前做过这件事,但我似乎不记得我是如何做的,也无法找到我做的项目。这就像解决方案刚刚消失在我身上...... *poof*。魔法。

编辑:更改为models.ForeignKey.

Ben*_*yer 5

你可以在你的 models.py 中使用类似 limit_choices_to 的东西:

category = model.ForeignKey(Category,limit_choices_to={'type':'the type you want'}
Run Code Online (Sandbox Code Playgroud)

如果您想要更动态或更详细的内容,您可以在ModelForm的init中指定特定字段的自定义查询集,例如:

self.fields['category'].queryset = Category.objects.filter(type='type_you_wanted')
Run Code Online (Sandbox Code Playgroud)

如果您想根据在表单中选择的 category.type 动态显示类别,那么您应该看到:https : //simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or -chained-dropdown-list-with-django.html