tags:

views:

32

answers:

1

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)

+2  A: 

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 this way, 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').

Daniel
I could just slap a `lambda:` in front of it to make it callable, couldn't I?
Mark
yeah, I thought of that after i posted :)
Daniel