我有一个有IntegerField
attr的课程。在它的ModelForm
中,在这个attr的字段中,我需要发送一个String,稍后它将在视图中处理后存储一个Integer。问题是Django不允许这样做,当我使用form.cleaned_data.get('myattr')
时,它说这是错误的,因为它应该是一个整数。
class Student(models.Model):
teacher = models.IntegerField(null=False) # I'm saving teacher's key here
class Teacher(models.Model:
name = models.CharField(max_length= 50, null=False)
key = models.IntegerField(null=False)
class StudentForm(forms.ModelForm):
teacher = forms.ModelChoiceField(queryset=Teacher.objects.all(), label='Select the teacher')
因此,当用户选择学生的教师时,该选择字段将显示可用教师的姓名。但在模型中它会存储他们的密钥,我在视图中管理。
views.朋友:
teacher = form.cleaned_data.get('teacher') # it has the name
teacher = Teacher.objects.get(name=teacher).key # getting the key in order to store an Integer, but Django is banning my code before anyway.
如何在不更改模型数据类型的情况下处理此问题?
我甚至在表单字段中添加了to_field_name
,其中包含教师密钥的值。
这里更好的方法是在学生和教师之间建立关系(使用外键)。
根据您的应用程序的需要,这里是如何做的:
如果一个学生可以有几个老师,一个老师可以有几个学生:https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/
如果一个学生只能有一个老师,但老师可以有多个学生:https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/
如果一个学生只能有一个老师,而一个老师只能有一个学生:https://docs.djangoproject.com/en/2.1/topics/db/examples/one_to_one/
这是管理它的最佳方式。那么你只需要在学生表格中映射学生模型,如:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
#you can add the list of all the fields you want there
fields = ['teacher']
一个额外的步骤是定义模型的str方法,以便Django将您的模型的字符串表示与您的表单相关联(这里有一个很好的方式在学生表单中显示教师)。
class Teacher(models.Model):
name = models.CharField(max_length= 50, null=False)
#place other fields here ...
def __str__(self):
#if you print a Teacher django will return the string corresponding to the teacher name
return self.name