Django在__init__中获取模型ID

时间:2016-02-04 05:19:18

标签: python django

这是我的代码:

class PreEncounterAttendanceForm(ModelForm):

    class Meta:
        model = PreEncounterAttendance
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(PreEncounterAttendanceForm, self).__init__(*args, **kwargs)
        this_class = self.instance.pre_encounter_class.id
        visitors = Visitor.objects.exclude(id__in=PreEncounterAttendance.objects.all().exclude(pre_encounter_class__id=this_class).values_list('student', flat=True))
        self.fields['student'].queryset = visitors

当我手动输入数字时,它会起作用,但当我使用self.instance.pre_encounter_class.id时,它会失败,因为它是NoneType

还有其他办法吗?

修改 发现了这个问题。我必须先检查实例ID是否存在:

class PreEncounterAttendanceForm(ModelForm):
class Meta:
    model = PreEncounterAttendance
    fields = '__all__'

def __init__(self, *args, **kwargs):
    super(PreEncounterAttendanceForm, self).__init__(*args, **kwargs)
    if self.instance.id:
        if self.instance.pre_encounter_class.id:
            this_class = self.instance.pre_encounter_class.id
            visitors = Visitor.objects.exclude(id__in=PreEncounterAttendance.objects.all().exclude(pre_encounter_class__id=this_class).values_list('student', flat=True))
            self.fields['student'].queryset = visitors
    else:
        visitors = Visitor.objects.exclude(id__in=PreEncounterAttendance.objects.all().values_list('student', flat=True))
        self.fields['student'].queryset = visitors

1 个答案:

答案 0 :(得分:0)

一种可能的方法是从视图中传递kwargs中的class id,然后在调用super()之前弹出它:

def __init__(self, *args, **kwargs):
    this_class = kwargs.pop('class_id', None)
    super(PreEncounterAttendanceForm, self).__init__(*args, **kwargs)    
    visitors = Visitor.objects.exclude(id__in=PreEncounterAttendance.objects.all().exclude(pre_encounter_class__id=this_class).values_list('student', flat=True))
    self.fields['student'].queryset = visitors