Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django rest框架中的相似用户名生成_Python_Django - Fatal编程技术网

Python django rest框架中的相似用户名生成

Python django rest框架中的相似用户名生成,python,django,Python,Django,当用户指定的用户名存在于数据库中,但不存在于数据库中时,我希望生成类似的用户名(至少3个)。即使不存在签入数据库的情况,但我需要一个包来生成类似的随机名称,我可以循环检查是否存在。请建议我个人制作一个类似这样的生成器: def get_similar_usernames(username): yielded = 0 n = 0 existing = User.objects.only("username") while yielded < 3:

当用户指定的用户名存在于数据库中,但不存在于数据库中时,我希望生成类似的用户名(至少3个)。即使不存在签入数据库的情况,但我需要一个包来生成类似的随机名称,我可以循环检查是否存在。请建议我个人制作一个类似这样的生成器:

def get_similar_usernames(username):
    yielded = 0
    n = 0
    existing = User.objects.only("username")
    while yielded < 3:
        potential_username = "{username}{suffix}".format(
            username=username,
            suffix=n
        ))
        for user in existing:
            if user.username == potential_username:
                break
        else:
            yielded += 1
            yield potential_username
        n += 1

当然,建议新用户名的精确算法将取决于您。

感谢您的快速回复
suggested_usernames = [name for name in get_similar_usernames(username)]