この質問のために簡略化された2つのモデルがあります。ではArticle
モデル、どのように私は制限することができchoices=
、フィールドのをArticle.status
内のエントリに基づいてCategory
、特定の持っているモデルCategory.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)
透明性のために、私は以前にこれを行ったことがあることを知っていますが、私がそれを行ったプロジェクトをどのように覚えているか、または見つけることができないようです。まるで解決策が私に消えたようです... * poof *。魔法。
編集:に変更されましたmodels.ForeignKey
。
models.pyでlimit_choices_toのようなものを使用できます:
category = model.ForeignKey(Category,limit_choices_to={'type':'the type you want'}
より動的な、またはより詳細なものが必要な場合は、次のようなModelFormの初期化で特定のフィールドのカスタムクエリセットを指定できます。
self.fields['category'].queryset = Category.objects.filter(type='type_you_wanted')
フォームで選択されたcategory.typeに応じてカテゴリを動的に表示する場合は、次のように表示されます:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or -chained-dropdown-list-with-django.html
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加