You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行Django脚本填充模型异常:员工表无法写入数据求助

Django填充脚本执行异常:仅Sector表写入成功,Employee表无数据

我编写了一个数据库表填充脚本,通过python manage.py shell < script.py命令执行,此前多次运行正常,但现在只有Sector表能成功添加s1数据,Employee表完全无法写入。但手动在shell中逐行执行脚本代码时,Employee表又能正常写入数据。

脚本代码

import names
from app.models import Employee, Sector
from random import randint

s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save()
print("start of the loop")
for i in range(10):
       n = names.get_full_name().split(" ")
       print(n[0] + " " + n[1])
       p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2))
       p.save()
print("end of the loop")

执行日志

(.env) λ python manage.py shell < quiz/script/fillTable.py
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> --- start of the loop ---
>>> ... ... ... ... ... ... ... ... ... Bertha Lucchese
David Berardi
... # 此处省略其余姓名
Esteban Albers
>>> --- end of the loop ---
>>>
now exiting InteractiveConsole...

问题原因及解决办法

核心原因

通过重定向方式执行脚本时,Django的事务未自动提交。手动逐行执行时,shell会在每步操作后自动处理事务提交;但重定向输入脚本时,整个脚本执行流程结束后,事务未触发提交,导致Employee的数据被回滚。

解决方法1:手动提交事务

在脚本末尾添加事务提交代码,强制提交所有未完成的事务:

import names
from app.models import Employee, Sector
from random import randint
from django.db import transaction  # 导入事务模块

s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save()
print("start of the loop")
for i in range(10):
       n = names.get_full_name().split(" ")
       print(n[0] + " " + n[1])
       p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2))
       p.save()
print("end of the loop")
transaction.commit()  # 手动提交事务

解决方法2:改用shell命令直接执行脚本内容

避免重定向输入,改用-c参数直接读取脚本内容执行,让事务正常提交:

python manage.py shell -c "$(cat quiz/script/fillTable.py)"

解决方法3:排查潜在错误(可选)

如果上述方法无效,可能是create_user过程中存在隐藏错误(如字段验证失败、重复主键等),重定向执行时错误信息被吞。可以在脚本中加入异常捕获,查看具体报错:

import names
from app.models import Employee, Sector
from random import randint

s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save()
print("start of the loop")
for i in range(10):
    try:
        n = names.get_full_name().split(" ")
        print(n[0] + " " + n[1])
        p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2))
        p.save()
        print(f"成功创建员工: {n[0]} {n[1]}")
    except Exception as e:
        print(f"创建员工失败: {str(e)}")
print("end of the loop")

内容的提问来源于stack exchange,提问作者problème0123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:05:31