开发者

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 func开发者_运维百科tion 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


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

promotion_code = models.CharField(max_length=20,unique=True,default=code_generate)


As indicated in the other answer, the simplest way to get a random string is as follows:

str(random.random())[2:]

Altho' it is a string of numbers. Fair enough, until you would want to replace it eventually with sha.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜