所以我在我的模型中添加了FileField
:
def sig_directory_path(instance, filename):
try:
ext = filename.split('.')[-1]
except:
ext = ""
filename = '{}.{}'.format(uuid4().hex, ext)
return 'sig/{0}'.format(filename)
ServiceReportData(models.Model):
...
# Newly added.
ca_technicianSignatureImage = models.FileField(null=True, blank=True, verbose_name="Technician Signature", upload_to=sig_directory_path)
我已经创建了自动迁移并迁移了更改。因此,数据库现在null
列的值为ca_technicianSignatureImage
。
然后我想为此字段创建数据迁移,因为我不想要该字段的空值:
from django.core.files.base import ContentFile
from django.db import migrations
# File content.
no_image_svg_content = """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="200"
height="150">
<rect
width="199"
height="149"
x="0.5"
y="0.5"
id="rect2824"
fill="#ffffff" stroke="#999999" stroke-width="1"/>
<text
x="64.648438"
y="79.863152"
id="text2818"
font-size="24"
font-weight="bold" text-align="center" text-anchor="middle" fill="#999999" stroke="none" font-family="Sans">
<tspan
x="100"
y="60"
id="tspan2820">No image</tspan>
<tspan
x="100"
y="90"
id="tspan2822">available</tspan>
</text>
</svg>
"""
def set_signatures(apps, schema_editor):
no_image_data = ContentFile(no_image_svg_content)
ServiceReportData = apps.get_model('mism', 'ServiceReportData')
for service_report in ServiceReportData.objects.all():
if service_report.ca_customerSignatureImage is None:
service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data)
class Migration(migrations.Migration):
dependencies = [
('mism', '0004_auto_20180131_1651'),
]
operations = [
migrations.RunPython(set_signatures, migrations.RunPython.noop),
]
运行此迁移不会更改数据库。我无法弄清楚如何去做。简单地说,如果字段为空,我只想在字段中放置一个默认的.svg文件。怎么做到这一点?
答案 0 :(得分:1)
您还需要调用实例的save()方法:
service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data)
service_report.save()
或作为快捷方式使用文件保存方法的save=True
:
service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data, save=True)
答案 1 :(得分:0)
这个错误很简单。
这不是检查FileField是否为null的正确方法:
if service_report.ca_customerSignatureImage is None:
而是必须这样做:
if service_report.ca_customerSignatureImage.name is None: