在文件上传django中使用外键

时间:2016-09-26 12:59:02

标签: django

我有两个模型如下:

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模型的实例并保存它。我是否需要首先创建LabelModelControlModel的实例并上传这些文件,然后创建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调用,如果其中一个失败,恢复它可能会有点痛苦......

0 个答案:

没有答案