从shell中更新Django模型对象字段



模型字段仅显示4个字符的邮政编码,例如:1234

我想通过添加"0"将所有4个字符的邮政编码更改为5个字符。开头,例如:01234

试图从shell中找到这样做的方法因为我有几千个对象

from app.models import Entry

我试着:

Entry.objects.filter(len(zip_code)==4).update("0"+zip_code)

Entry.objects.filter(len(zip_code)==4).update(f("0"+{zip_code}))

错误返回:

Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'zip_code' is not defined

您可以对此进行迁移:

首先,创建一个空迁移:
python manage.py makemigrations your_app_name --empty

在新创建的迁移中定义函数:

def update_zipcodes(apps, schema):
YourModel = apps.get_model("your_app_name", "YourModel")  # django will retrieve your model here

for obj in YourModel.objects.all():
if len(obj.zip_code) == 4:
old_zip_code = obj.zip_code
obj.zip_code = f'0{old_zip_code}'
obj.save()

然后在列表操作中调用该函数(在文件的底部)。你的列表应该像这样

operations = [
# migrations.RunPython.noop can be replaced here with a reverse function
# (in case you want to "un-apply" that migration later for some reason)
migrations.RunPython(update_zipcodes, migrations.RunPython.noop),
]

最后,通过调用

应用迁移
python manage.py migrate

最新更新