模型字段的随机/非恒定默认值? [英] Random/non-constant default value for model field?
问题描述
我有一个看起来像这样的模型
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)
您会注意到, key
的默认值是一个随机的16个字符的字符串.问题是,我认为此值已被缓存并连续使用多次.有什么办法可以让我每次都得到一个不同的字符串吗?(我不在乎唯一性/冲突)
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)
推荐答案
是的,仅在初始化模型元类时才会设置默认值,而在创建SecretKey的新实例时则不会设置默认值.
Yes, the default will only be set when the Model metaclass is initialized, not when you create a new instance of 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)
您当然也可以在模型的 __ init __
函数中设置值,但是可调用函数更简洁,并且仍可以使用 model = SecretKey(key ='blah')
.
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')
.
这篇关于模型字段的随机/非恒定默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!