Skip to main content
 首页 » 编程设计

python之Django 唯一随机作为默认值

2024年10月25日37oomusou

在将某个值指定为默认值时,有什么方法可以检查该值是否存在于模型中?如果分配值存在(它不是唯一的),则生成另一个值。 (阅读评论):

def unique_rand(): 
    return ... # Generate a random string with 8 characters length 
               # It shouldn't exists among other persons 
               # If exists then generate another random string 
 
 
class Person(models.Model): 
    code = models.CharField(max_length=8, unique=True, default=unique_rand()) 

也许解决方法不能在 unique_rand 中,而是在 Person 类中的某个地方。 我不想覆盖 save 方法,因为在 save 之前我需要 code。另外,我不想使用 uuid randoms。

请您参考如下方法:

只需测试循环中生成的代码是否存在。

from django.contrib.auth.models import User 
 
def unique_rand(): 
    while True: 
        code = password = User.objects.make_random_password(length=8) 
        if not Person.objects.filter(code=code).exists(): 
            return code 
 
class Person(models.Model): 
    code = models.CharField(max_length=8, unique=True, default=unique_rand) 

请注意,default=unique_rand 参数中没有圆括号。

如果您想限制尝试次数,请将循环从 while 更改为 for:

def unique_rand(): 
    for _ in range(5): 
        ... 
    raise ValueError('Too many attempts to generate the code')