让我们聊聊这个话题, django如何存数据至mysql数据表里面,你会用什么方法?正常情况下,我们form逻辑处理后,直接form.save(),是,这个方法没毛病;但有没有其他的方法呢?假如我们有这样一个需要,比如说,我们我们现在有100台服务器要进行一个部署代码的操作,那么每个服务器的操作我们都要在数据库里面做记录,以便我们审记时好追溯!此时,使用form.save方法好像不能满足需求的,这就需要使用方法二的方法,如下演示:
方法一:
if form.is_valid():
......
new_form = form.save(commit=False)
new_form.fun = 'p2p.scp'
new_form.deploy_path = deploy_path
new_form.operate = operate
new_form.status = status
new_form.context = json.dumps(context, sort_keys=True)
new_form.save()
form.save()
方法二:
def do_copy_control(**kwargs):
target_server = get_target_server()
while target_server:
command = "/usr/bin/python /data/agent_scripts/scp_agent.py %s %s %s %s %s %s %s %s" % (
kwargs['source_server'].networks.private_address,
kwargs['source_server'].superuser,
kwargs['source_server'].superuser_pass,
kwargs['source_path'], kwargs['deploy_path'], kwargs['release_abs_path'],
kwargs['compress_file'], kwargs['md5sum']
)
data = {
'expr_form': 'list',
'client': 'local',
'fun': 'cmd.run',
'tgt': target_server.host_name,
'arg': command,
}
salt = SaltApi()
salt.get_token()
header = salt.get_header()
context = process(header, **data)
if regex_match_error(json.dumps(context)) is True:
status = True
else:
status = False
# save to mysql
storage_dict = {
'operate': kwargs['operate'],
'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'client': 'local',
'use_zone': kwargs['use_zone'],
'fun': 'cmd.run',
'deploy_path': kwargs['deploy_path'],
'release_path': kwargs['release_abs_path'],
'content': kwargs['content'],
'status': status,
'context': context,
'departments_id': kwargs['departments_id'],
'repository_name_id': kwargs['repository_name_id'],
'zones_id': kwargs['zones_id'],
}
storage = Release.objects.create(**storage_dict)
for item in kwargs['server']:
storage.tgt.add(item)
logging_out("source_server: %s target_server: %s result: %s" % (kwargs['source_server'].host_name,
target_server.host_name, context))
if regex_match_error(context):
thread = threading.Thread(target=do_copy_control, kwargs=kwargs)
thread.start()
else:
add_error_list(target_server.host_name)
target_server = get_target_server()
storage = Release.objects.create(**storage_dict),storage_dict就是我们每行的数据, Release.objects.create()是存入数据库的方法,而storage.tgt.add则是对manytomany的外键进行一个处理!