我已经实现了为每个 RetailerMaster 上传多个文件的功能(作为外键)。一旦我将此模型迁移到 microsoft sql server,就会创建 FileUpload 模型而没有 django 应该自动创建的主键。此外,如果我上传多个文件,那么数据库中只会创建一个记录,并且它会不断更新每个文件。
模型.py
class RetailerMaster(models.Model):
id = models.PositiveIntegerField(unique=True)
name = models.CharField(max_length=1000)
address = models.CharField(max_length=4000)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
pincode = models.CharField(max_length=100)
contact_name = models.CharField(max_length=500)
email = models.EmailField()
phone = models.CharField(max_length=15)
erp = models.CharField(max_length=1000)
remark = models.CharField(max_length=4000)
def __str__(self):
return self.id
class FileUpload(models.Model):
retailer = models.ForeignKey(RetailerMaster, on_delete=models.CASCADE),
file = models.FileField(upload_to='files')
file_upload_datetime = models.DateTimeField()
file_name = models.CharField(max_length=1000)
视图.py
retailer = RetailerMaster.objects.get(retailer_id=retailer_id)
register_complete = retailer
files = request.FILES.getlist('file')
file_upload_datetime = file_upload_form.cleaned_data['file_upload_datetime']
for f in files:
print(f.name)
file_instance = FileUpload(register_complete.id,f,file_upload_datetime,f.name)
file_instance.save()
迁移文件
migrations.CreateModel(
name='FileUpload',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to='files')),
('file_upload_datetime', models.DateTimeField()),
('file_name', models.CharField(max_length=1000)),
],
)
为什么迁移文件没有外键?
模板文件
<div id="registrationForm">
<form
action="{% url 'retail_forms:file-upload' %}"
method="post"
enctype="multipart/form-data"
>
{% csrf_token %} {{ retailer_registration_form|crispy }} {{ file_upload_form|crispy }}
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
例如:如果上传了两个文件 001.xlsx 和 002.xlsx,则数据库中会发生以下情况。作为实际结果,插入一条记录而不是两条记录,并且使用从多个文件上传的最后一个文件更新相同的记录。
谁能帮助为什么不插入记录而只是更新了记录。