[英]django - creating users making their fullname unique
i need small help in the logic of creating user making his name unique: 在创建使他的名字唯一的用户的逻辑上,我需要小的帮助:
i have a django user profile. 我有django用户个人资料。 i am creating users in this way: 我以这种方式创建用户:
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()
You want to check for the IntegrityError
on save and update accordingly. 您要在保存时检查IntegrityError
并相应地更新。 Doing a query to check for the names existence creates a race condition where you can search then two separate threads try to create the same fullname at the same time. 进行查询以检查名称是否存在会创建一个竞争条件,您可以在其中搜索然后两个单独的线程尝试同时创建相同的全名。
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)
For this purpose it would be better to use form https://docs.djangoproject.com/en/dev/topics/forms/ . 为此,最好使用表格https://docs.djangoproject.com/en/dev/topics/forms/ 。 But if you won't to use forms, you can do it that way: 但是,如果您不使用表格,可以这样做:
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
Note, that field 'name' in UserProfile model must have unique=True parameter https://docs.djangoproject.com/en/dev/ref/models/fields/#unique 请注意,UserProfile模型中的字段“名称”必须具有unique = True参数https://docs.djangoproject.com/en/dev/ref/models/fields/#unique
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.