gpt4 book ai didi

python - 我怎样才能用更少的冗余/复制粘贴来写这个?

转载 作者:行者123 更新时间:2023-11-28 19:39:29 26 4
gpt4 key购买 nike

我通常不会以最好的方式编写我的 Python 代码,因为我对它比较陌生,有人要求我对 Django 应用程序进行更改,因为代码看起来不太好。

这是它的样子:

@login_required
def submission_set_rank(request):

r1_obj_id = request.GET.get('rank1','')
r2_obj_id = request.GET.get('rank2','')
r3_obj_id = request.GET.get('rank3','')
r4_obj_id = request.GET.get('rank4','')
r5_obj_id = request.GET.get('rank5','')

#rate the first BallotStats object
ballot_1 = BallotStats.objects.get(object_id=r1_obj_id)
ballot_2 = BallotStats.objects.get(object_id=r2_obj_id)
ballot_3 = BallotStats.objects.get(object_id=r3_obj_id)
ballot_4 = BallotStats.objects.get(object_id=r4_obj_id)
ballot_5 = BallotStats.objects.get(object_id=r5_obj_id)

ballot_1.score += 5
ballot_2.score += 4
ballot_3.score += 3
ballot_4.score += 2
ballot_5.score += 1

ballot_1.save()
ballot_2.save()
ballot_3.save()
ballot_4.save()
ballot_5.save()

return HttpResponseRedirect('/submissions/results/film/')

事实证明,我意识到我一直都是这样写我的 Python 代码,有没有办法让它看起来更好,而不是占用 21 行以上的代码?

最佳答案

最大的问题不是代码的风格——而是您进行了 10 次查询:5 次用于获取对象,5 次用于更新对象。

使用 __in 过滤掉对象立刻:

@login_required
def submission_set_rank(request):
keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
ranks = [request.GET.get(key,'') for key in keys]
for ballot in BallotStats.objects.filter(object_id__in=ranks):
ballot.score += keys[ballot.object_id]
ballot.save()

return HttpResponseRedirect('/submissions/results/film/')

这将最多进行 6 次查询:1 次用于获取对象,5 次用于更新对象。

此外,您可以使用 commit_manually“标记” View 装饰器( commit_on_success 也适用于您)。应该speed up things significantly :

@login_required
@transaction.commit_manually
def submission_set_rank(request):
keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
ranks = [request.GET.get(key,'') for key in keys]
for ballot in BallotStats.objects.filter(object_id__in=ranks):
ballot.score += keys[ballot.object_id]
ballot.save()
transaction.commit()

return HttpResponseRedirect('/submissions/results/film/')

而且我有一种强烈的感觉,您甚至可以在单个更新查询中执行此操作。例如,通过使用 connection.cursor()直接在 executemany() 的帮助下:

@login_required
def submission_set_rank(request):
keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
ranks = [{'score': request.GET.get(key,''), 'id': key} for key in keys]

cursor = connection.cursor()
cursor.executemany("""
UPDATE
ballot_stats
SET
score = score + %(score)s
WHERE
object_id = %(id)s
""", ranks)

return HttpResponseRedirect('/submissions/results/film/')

确保字段名和表名正确。

关于python - 我怎样才能用更少的冗余/复制粘贴来写这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com