Django自动为表单中的外键赋值?

时间:2015-10-10 19:31:22

标签: python django database foreign-keys

我正在我的模板中呈现一个表单,其中“患者用户”提交约会。我有这个尴尬的模型层次结构,我试图解决。

我有一个appointmentRequest,它接收患者的外键,其中患者由批准号和django内置的用户对象的外键组成。

我基本上(在表格提交预约时)自动填写患者外键数据。这可能吗?

Models.py

#This patient model will extend the user class so we can add the associated medical data for the user
class Patient(models.Model):
    phone_number = PhoneNumberField(blank = True)
    email_address = models.EmailField(blank = True, max_length=254)
    user = models.OneToOneField(User, unique=True,  blank=True, default="", null=True)
    approved = models.IntegerField(default=0, null=False)



#Class for the patients to schedule appointments for their associated doctor
class PatientAppt(models.Model):
    date = models.DateTimeField(auto_now=False, auto_now_add=False, unique=True)
    doctor = models.ForeignKey(Doctor, unique=False, blank=True, default="")
    pain_level = models.IntegerField(validators=[MinValueValidator(0),
                                       MaxValueValidator(10)], default=0)
    medical_conditions = models.CharField(max_length=1000, default="None")
    allergies = models.CharField(max_length=1000, default="None")
    user = models.ForeignKey(Patient, unique=False, blank=True, default="")

1 个答案:

答案 0 :(得分:0)

如果您正在使用django表单(您应该使用它),我认为最好的方法是覆盖save方法并传递患者对象。通过隐藏字段将id传递给表单意味着您无论如何都需要验证服务器端,而如果您从会话中传递了ID,则表示它是安全的。

# Your View
def post(self, request):
    ...
    if context['form'].is_valid():
        context['form'].save(patient=request.user.patient)

# Your form
def save(self, commit=True, patient=patient):
    self.instance.user = patient
    return super(PatientApptForm, self).save(commit=commit)