模型字段的随机/非常量默认值?

时间:2021-09-07 21:34:01

I've got a model that looks something like this

我有一个看起来像这样的模型

class SecretKey(Model):
    user = ForeignKey('User', related_name='secret_keys')
    created = DateTimeField(auto_now_add=True)
    updated = DateTimeField(auto_now=True)
    key = CharField(max_length=16, default=randstr(length=16))
    purpose = PositiveIntegerField(choices=SecretKeyPurposes)
    expiry_date = DateTimeField(default=datetime.datetime.now()+datetime.timedelta(days=7), null=True, blank=True)

You'll notice that the default value for key is a random 16-character string. Problem is, I think this value is getting cached and being used several times in a row. Is there any way I can get a different string every time? (I don't care about uniqueness/collisions)

您会注意到key的默认值是一个随机的16个字符的字符串。问题是,我认为这个值被缓存并连续多次使用。我有什么方法可以每次都得到一个不同的字符串吗? (我不关心唯一性/碰撞)

1 个解决方案

#1


10  

Yes, the default will only be set when the Model metaclass is initialized, not when you create a new instance of SecretKey.

是的,默认只会在初始化Model元类时设置,而不是在创建SecretKey的新实例时设置。

A solution is to make the default value a callable, in which case the function will be called each time a new instance is created.

解决方案是使默认值成为可调用的,在这种情况下,每次创建新实例时都会调用该函数。

def my_random_key():
    return randstr(16)

class SecretKey(Model):
    key = CharField(max_length=16, default=my_random_key)

You could, of course, also set the value in the model's __init__ function, but callables are cleaner and will still work with standard syntax like model = SecretKey(key='blah').

当然,您也可以在模型的__init__函数中设置值,但是callables更干净,仍然可以使用标准语法,如model = SecretKey(key ='blah')。

#1


10  

Yes, the default will only be set when the Model metaclass is initialized, not when you create a new instance of SecretKey.

是的,默认只会在初始化Model元类时设置,而不是在创建SecretKey的新实例时设置。

A solution is to make the default value a callable, in which case the function will be called each time a new instance is created.

解决方案是使默认值成为可调用的,在这种情况下,每次创建新实例时都会调用该函数。

def my_random_key():
    return randstr(16)

class SecretKey(Model):
    key = CharField(max_length=16, default=my_random_key)

You could, of course, also set the value in the model's __init__ function, but callables are cleaner and will still work with standard syntax like model = SecretKey(key='blah').

当然,您也可以在模型的__init__函数中设置值,但是callables更干净,仍然可以使用标准语法,如model = SecretKey(key ='blah')。