如何在 views.py 中创建 Django 模型?

How can I create a Django model in views.py?

在对象 "Patient" 的 DetailView 页面中,我有一个表单。填写并提交表单后,我想创建一个 "Location" 对象。然后,我想创建一个指向我们在 DetailView 中查看的 "Patient" 对象的 ForeignKey。

如您所见,如果表单有效,我将调用模型构造函数,保存信息并将其连接到患者对象。但是,当我检查 Django Admin 时,我看不到创建的新对象。我完全是即兴创作的,因为我在网上找不到例子。是这样吗?

class PatientDetailView(DetailView, FormMixin):
    model=Patient
    form_class = PastLocationForm
    #template_name = 'patient_detail.html'

    def get_success_url(self):
        return reverse('patient_detail', kwargs={'pk': self.object.pk})

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        self.object = self.get_object()

        form = self.get_form()

        if form.is_valid():
            pastLocationDetail = Location()
            setattr(pastLocationDetail,'location',str(form.cleaned_data['location']).split(',')[0])
            setattr(pastLocationDetail,'address',str(form.cleaned_data['location']).split(',')[1].split(', ')[0])
            setattr(pastLocationDetail,'district',str(form.cleaned_data['location']).split('District: ')[1].split(',')[0])
            setattr(pastLocationDetail,'grid_x',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[0])
            setattr(pastLocationDetail,'grid_y',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[1][:-1])
            setattr(pastLocationDetail,'date_from',form.cleaned_data['date_from'])
            setattr(pastLocationDetail,'date_to',form.cleaned_data['date_to'])
            setattr(pastLocationDetail,'details',form.cleaned_data['details'])
            setattr(pastLocationDetail,'patient', self.object)

            return self.form_valid(form)
        else:
            return self.form_invalid(form)

位置模型

class Location(models.Model):
    patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True)
.
.

注意:我打印了两个对象

print(type(self.object))
print(pastLocationDetail)

一切似乎都很好。实在不明白为什么不写入数据库

你调用了save方法吗? Django orm 需要调用 save 将实例数据写入数据库。看到这个 Django model instance docs.

if form.is_valid():
    pastLocationDetail = Location()
    ...
    pastLocationDetail.save()  # this line required for writing model instance to database 
    return self.form_valid(form)
else:
    return self.form_invalid(form)

还建议您查看this document以便更好地使用表格。