Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, randomization of "default" parameter of a model

I want to set the "default" value as a randomly generated String for the promotion_code part of my Promotion model, for that the code_generate function is used.

The issue with the code below that it seems like default=code_generate() generates this random string once every server start thus assigning the same value. I can see that by the admin panel, every time I try to generate a new Promotion, it gives me the exact same string.

#generate a string, which is not already existing in the earlier Promotion instances
def code_generate():
    while 1:
        from django.conf import settings
        import random, string
        prom_code = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
        try:
            Promotion.objects.get(promotion_code=prom_code)
        except:
            return prom_code

class Promotion(models.Model):
    purchase = models.ForeignKey('Purchase')
    promotion_code = models.CharField(max_length=20,unique=True,default=code_generate())

How can I make it random ?

Regards

like image 554
Hellnar Avatar asked Feb 13 '10 14:02

Hellnar


People also ask

How to set default value for a field in Django model?

Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value.

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).


1 Answers

You need to pass a callable as default, not call the callable:

promotion_code = models.CharField(max_length=20,unique=True,default=code_generate)
like image 150
Hellnar Avatar answered Oct 13 '22 09:10

Hellnar