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

时间:2014-06-20 14:50:29

标签: python django

我需要在创建用户的逻辑方面提供一些小帮助,使他的名字独一无二:

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

2 个答案:

答案 0 :(得分:2)

您想要在保存时检查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)

答案 1 :(得分:1)

为此目的,最好使用表格https://docs.djangoproject.com/en/dev/topics/forms/。但是如果你不使用表格,你可以这样做:

i = 0
orig_fullname = fullname
created = False
while not created:
    profile, created = UserProfile.objects.get_or_create(name=fullname)
    if not created:
        i+=1
        fullname = orig_fullname + str(i)
# there you have new user's profile

注意,UserProfile模型中的字段'name'必须具有unique = True参数https://docs.djangoproject.com/en/dev/ref/models/fields/#unique