Python 为什么这个循环总是返回原始参数?
我有一个检查用户名的循环。 如果用户名存在,我想增加每个循环的计数器。 然后将该Id附加到用户名 这个循环总是返回传递的原始参数,我不知道为什么。我让它在forms.py中的表单上执行Python 为什么这个循环总是返回原始参数?,python,django,loops,Python,Django,Loops,我有一个检查用户名的循环。 如果用户名存在,我想增加每个循环的计数器。 然后将该Id附加到用户名 这个循环总是返回传递的原始参数,我不知道为什么。我让它在forms.py中的表单上执行def save def check_username(self, username): """ check if username is taken. if it is then increment the counter and append to the username """
def save
def check_username(self, username):
"""
check if username is taken. if it is then increment the counter and append to the username
"""
counter = 001
if User.objects.filter(username__iexact=username).exists():
counter += 1
username += str(counter)
self.check_username(username)
return username
检查
if User.objects…
条件的有效性,因为username
如果进入该块,应该更改。您可能应该使用return self。检查if
块中的用户名(username)
,否则,递归调用不会有多大作用
这里的柜台可能也不是你想要的。您将继续在尝试的每个用户名的末尾添加“2”,例如username
->username2
->username2
->username22
话虽如此,这里的while
循环肯定更容易阅读。我想试试这样的东西:
def check_username(self, username):
counter = 1
new_username = username
while not User.objects.filter(username__iexact=new_username).exists():
counter += 1
new_username = username + str(counter)
return new_username
你在做一个if,那不是一个循环。你应该用一段时间。哈哈,你是对的,这不是一个循环。。。但我回到了同一个def。然而,一个while循环就是答案。