Django公司表单.py获取ModelChoiceField的主键

2024-06-28 11:06:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我做了很多研究,试图找出如何根据另一个字段的选定值(向下钻取)筛选字段。下面是我正在研究的一个例子。我见过一些应用程序,看起来像django智能选择(django: Drill down select options?)一样工作,但它似乎不适合我,它似乎没有我所需要的那样可靠。在

forms.py 

from django.forms import ModelForm
from .models import CurriculumIntervention
from Lesson.models import Curriculum
from Lesson.models import CurriculumLesson

class CurriculumInterventionEducatorsForm(ModelForm): 

    def __init__(self, *args, **kwargs):
        super(CurriculumInterventionEducatorsForm, self).__init__(*args, **kwargs)
        curriculum = self.fields['curriculum'] #This is a ModelChoiceField

        if self.instance:
            self.fields['curriculum_lesson'].queryset= \
                CurriculumLesson.objects.filter(curriculum= **____**)#<-- what do I put here to get the curriculum's primary key value?
        else: 
            self.fields['curriculum_lesson'].queryset= None

视图和模板工作正常。我只是不知道如何从第一个ModelChoiceField获取主键,以用于第二个ModelChoiceField的查询。如果我把一个随机ID值放在空白的1中,它会把所有的东西都过滤到那个ID。我想我需要知道如何获取QualESET中使用的MyDyCoice字段的选定值。也许我走错了路,但这就是我现在的处境。我想知道是否需要使用视图来确定所选的值并将其传递给表单(就像这篇文章所做的Django filter the queryset of ModelChoiceField


Tags: djangofromimportselffieldsinitmodelsforms