在将某个值指定为默认值时,有什么方法可以检查模型中是否存在该值?如果分配值存在(不唯一),则生成另一个值。 (阅读评论):
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
方法,因为我需要code
before save
。另外,我不想使用uuid
随机数。
只需测试循环中生成的代码是否存在。
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
to for
:
def unique_rand():
for _ in range(5):
...
raise ValueError('Too many attempts to generate the code')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)