Skip to main content
 首页 » 编程设计

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

2024年08月27日35yjmyzz

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

我有一个 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)