【问题标题】:Django ModelForm how to display only a subset of ModelDjango ModelForm如何只显示模型的一个子集
【发布时间】:2022-01-09 04:22:46
【问题描述】:

我有一个 django 模型用于预约医生

class Appointment(models.Model):
    patient=models.ForeignKey(Patient,on_delete=models.SET_NULL,null=True)
    date=models.DateField(default=datetime.date.today)
    doctor=models.ForeignKey(Profile,on_delete=CASCADE)
    status=models.CharField(max_length=12,default="open")
    def __str__(self):
        return self.name

Doctor 是 Profile 模型中的角色之一。我的表单是这样定义的

class AppointmentForm(forms.ModelForm):
    class Meta:
        model=Appointment
        exclude = ['id']
    def __init__(self,*args,**kwargs):
        super().__init__(*args, **kwargs)
        self.helper=FormHelper()
        self.helper.layout=Layout(
            Row(
                Column('patient',css_class="form-control, col-md-4 mb-0"),
                Column('date',css_class="form-group, col-md-4 mb-0"),
                Column('doctor',css_class="form-group, col-md-4 mb-0"),
                css_class='row '
            ),
            Submit('btn_save', 'Save',css_class='btn-success')
        )

当使用清晰表单显示表单时,会显示 Profile 模型的所有用户。

如何仅显示角色为 DoctorProfiles

【问题讨论】:

    标签: django django-models django-crispy-forms modelform


    【解决方案1】:

    在您的 init 函数中,您可以过滤用于显示医生选择的查询集:

    class AppointmentForm(forms.ModelForm):
    
        def __init__(self,*args,**kwargs):
            super().__init__(*args, **kwargs)
    
            self.fields['doctor'].queryset = Profile.objects.filter(role="Doctor")
    
    

    您可以在How do I filter ForeignKey choices in a Django ModelForm? 上进一步了解此内容

    【讨论】:

      猜你喜欢
      • 2022-06-12
      • 2014-01-02
      • 2012-10-24
      • 2012-05-24
      • 1970-01-01
      • 2015-11-09
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多