每次将模型对象保存到数据库时,都要创建一个随机字符串

Joe*_*hew 0 django django-models

在我的models.py中,我有:

def MakeOTP():
    import random,string
    return ''.join(random.choices(string.digits, k=4))


class Prescriptionshare(models.Model):
    prid = models.AutoField(primary_key=True, unique=True)
    customer = models.ForeignKey(
        customer, on_delete=models.CASCADE, null=True)
    time = models.DateTimeField(default=timezone.now)
    checkin =models.ForeignKey(Checkins, on_delete=models.CASCADE, null=True)
    otp = models.CharField(max_length=5, default=MakeOTP())
Run Code Online (Sandbox Code Playgroud)

在我的django shell中,我尝试了以下内容:

pq = Prescriptionshare(customer = cus, checkin = chk)
pq.save()
Run Code Online (Sandbox Code Playgroud)

问题是,每次执行此操作时,我都会在otp字段中获得相同的字符串.字符串没有随机变化.为什么会这样?

JPG*_*JPG 5

除去()default=MakeOTP()

class Prescriptionshare(models.Model):
    # your code
    otp = models.CharField(max_length=5, default=MakeOTP) # here, remove the "()"
Run Code Online (Sandbox Code Playgroud)

在模型中进行更改后,您应该迁移数据库


为什么会这样?
如果你使用MakeOTP(),Django获取函数的输出,就像你使用MakeOTP(没有括号)Django认为它是可调用函数.

也就是说,当使用paranthesis时,一旦运行迁移并且将其值用作默认值,则调用方法,并且当不使用paranthesis时,每次在创建对象时调用函数引用.