我有两个模型如下:
class LabelModel(models.Model):
labelled_image = models.FileField(upload_to='documents/label',
db_column='path', default='Some Value')
class Meta:
db_table = "label_images"
class ControlModel(models.Model):
control_image = models.FileField(upload_to='documents/control', db_column='path',
default='Some Value')
class Meta:
db_table = "control_images"
最后,我有一个复合模型如下:
class Document(models.Model):
labelled_image = models.ForeignKey(LabelModel, db_column='label')
control_image = models.ForeignKey(ControlModel, db_column='control')
现在在我看来,我有以下内容:
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
# Path to files
labelled_file = request.FILES['labelled_image']
control_file = request.FILES['control_image']
# How should I create the Document model instance?
DocumentForm
如下:
class DocumentForm(forms.Form):
labelled_image = forms.FileField(label='Select the Label image')
control_image = forms.FileField(label='Select a Control image')
我的问题是我现在应该如何创建Document
模型的实例并保存它。我是否需要首先创建LabelModel
和ControlModel
的实例并上传这些文件,然后创建Document
模型实例,或者有没有办法与Django一起完成?
[编辑]
按照@ sebb的评论我做了以下事情:
label_model = LabelModel(labelled_image=labelled_file)
label_model.save()
control_model = ControlModel(control_image=control_file)
control_model.save()
newdoc = Document.objects.create(labelled_image=label_model,
control_image=control_model)
这很有效。但是,我想知道是否必须执行这些多个save
调用,如果其中一个失败,恢复它可能会有点痛苦......