需求:点击ID跳出弹框,对这里面的数据进行修改走了很多弯路,最会采用的是将reviewers和watchers保存到数据库之前先把对应的数据库记录删掉,这相当于添加,这里最重要的是别忘了使用事务,这样一旦出现问题会回滚到之前的状态
def get_keys(d, value):
return [k for k, v in d.items() if v == value]
def reviewerRuleAdd(request):
check_reviewers = []
check_watchers = []
project = request.POST.get("project", None)
branch = request.POST.get("branch", None)
filename = request.POST.get("filename", None)
reviewers = request.POST.get("reviewers", None)
watchers = request.POST.get("watchers", None)
remark = request.POST.get("remark", None)
reviewlist = reviewers.split(',')
watcherlist = watchers.split(',')
regular = {'仓库': project, '分支名': branch, '文件名': filename}
try:
for key, value in regular.items():
re.compile(value)
except:
msgkey = get_keys(regular, value)
return JsonResponse({'check_msg': ''.join(msgkey) + '选项中,格式不合法,请输入一个正确的!'})
for name in set(reviewlist):
userbool = User.objects.filter(username=name).exists()
if userbool:
check_reviewers.append(name)
elif not userbool:
return JsonResponse({'msg': 'reviewers选项中,含有输入用户在系统不存在,请输入一个正确的!'})
new_watcherlist = list(set(watcherlist))
for i in range(0, len(new_watcherlist)):
userbool = User.objects.filter(username=new_watcherlist[i])
if len(userbool) > 0 and userbool[0].username == new_watcherlist[i]:
check_watchers.append(new_watcherlist[i])
elif len(userbool) == 0 or userbool[0].username not in new_watcherlist[i]:
return JsonResponse({'msg': 'watchers选项中,含有输入用户在系统不存在,请输入一个正确的!'})
current_id = Gerrit_Reviewer_Rule.objects.create(
project=project,
branch=branch,
filename=filename,
remark=remark)
if len(check_reviewers)>0:
for i in check_reviewers:
user_ = User.objects.filter(username=i)
for b in user_:
Gerrit_Reviewer_User.objects.create(gtrevuser_id=int(current_id.id),type_user='reviewers',user_id=int(b.id))
if len(check_watchers)>0:
for j in check_watchers:
user_ = User.objects.filter(username=j)
for n in user_:
Gerrit_Reviewer_User.objects.create(gtrevuser_id=int(current_id.id),type_user='watchers',user_id=int(n.id))
return JsonResponse({'info': 'Success!'})
一开始考虑是改了reviewers或者watchers就删除该条记录,发现很麻烦而且代码太长