繁体   English   中英

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

[英]django - creating users making their fullname unique

在创建使他的名字唯一的用户的逻辑上,我需要小的帮助:

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

为此,最好使用表格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模型中的字段“名称”必须具有unique = True参数https://docs.djangoproject.com/en/dev/ref/models/fields/#unique

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM