gpt4 book ai didi

python - django - 创建用户使其全名唯一

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:25 25 4
gpt4 key购买 nike

我在创建用户的逻辑上需要一点帮助,使他的名字独一无二:

我有一个 Django 用户配置文件。我以这种方式创建用户:

fullname = request.POST.get('fullname')
random_username = ''.join(random.sample(string.ascii_lowercase, 8))
new_user = User.objects.create_user(random_username, email, passwort)
##update siteprofile of this new user
userprofile = new_user.get_profile()

"""
i need to make this fullname unique with this logic:
for example john is the fullname of new user. i need to check if there are
other johns in db, if there is another user with this name, i will name the
user with 'john1'. if there are 2, the new user will get the name 'john3'
how can I check this in db in some efficient way?

"""
userprofile.name = fullname
userprofile.save()

最佳答案

您想在保存时检查 IntegrityError 并进行相应更新。执行查询以检查名称是否存在会产生竞争条件,您可以在其中搜索然后两个单独的线程尝试同时创建相同的全名。

from django.db import transaction

@transaction.commit_manually
def set_fullname(userprofile, fullname, i=0):
new_fullname = u"{}{}".format(fullname, str(i) if i else '')
try:
userprofile.fullname = new_fullname
userprofile.save()

transaction.commit()

return userprofile
except IntegrityError:
transaction.rollback()

i += 1
# Just recursively try until we a valid name. This could be problematic if you
# have a TON of users, but in that case you could just the filter before then to see
# what number to start from.
return set_fullname(userprofile, fullname, i)

userprofile = set_fullname(userprofile, fullname)

关于python - django - 创建用户使其全名唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24330068/

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