我在django中有一个模型,如下所示。
class Employee(models.Model):
name = models.CharField()
def setContactInfoProperty(key, value):
setattr(self.contactInfo, key, value)
self.contactInfo.save()
def getContactInfoProperty(key):
return getattr(self.contactInfo, key)
@phone.setter
def phone(self, value):
self.setContactInfoProperty('phone',value)
def phone(self):
return self.getContactInfoProperty('phone')
class ContactInfo(models.Model):
phone = models.IntegerField()
employee = models.OneToOneField('Employee', related_name='contactinfo')
由于传统原因,Phone的setter保留在Employee模型中。我现在有一个员工的django表格,我也想添加手机。所以我想把phone属性添加到EmployeeForm。
class EmployeeForm(forms.ModelForm):
phone = forms.IntegerField()
fields = ['name', 'phone']
但是当我保存表单时,手机没有保存。如何设置EmployeeForm的电话号码? 任何帮助将不胜感激。感谢。
答案 0 :(得分:1)
我认为您的模型设置不会使EmployeeForm
识别phone
字段,因此您需要手动保存:
# in views.py
if employee_form.is_valid():
new_employee = employee_form.save(commit=False)
new_employee.phone = employee_form.cleaned_data['phone']
new_employee.save()