当前位置: 动力学知识库 > 问答 > 编程问答 >

model - django always giving same default values

问题描述:

I have my payment_id generated based on UTC time and append 4 random characters to it. But when i call the function, the utc_now() and random_string(4) seems like they were only executed once.

class Payment(models.Model):

PAYMENT_STATUS_CHOICES = (

('P','Pending'),

('A','Paid'),

('C','Canceled'),

)

PAYMENT_TYPE_CHOICES = (

('E','Electrician'),

('S','Salesman'),

)

def __unicode__(self):

return '%s %s %s %s' % (self.payment_id,str(self.record_time),self.get_payment_type_display(),self.payment_status)

led_gu5_3_price = models.DecimalField(max_digits=10,decimal_places=2)

led_gu10_price = models.DecimalField(max_digits=10,decimal_places=2)

cfl_bc_price = models.DecimalField(max_digits=10,decimal_places=2)

cfl_es_price = models.DecimalField(max_digits=10,decimal_places=2)

cfl_sbc_price = models.DecimalField(max_digits=10,decimal_places=2)

cfl_ses_price = models.DecimalField(max_digits=10,decimal_places=2)

initial = models.DecimalField(max_digits=10,decimal_places=2)

record_time = models.DateTimeField(default=utc_now(),editable=False)

payment_id = models.CharField(max_length=10,default=utc_now().strftime('%y%m%d')+random_string(4),editable=False)

payment_status = models.CharField(max_length=1,choices=PAYMENT_STATUS_CHOICES,default='P')

payment_type = models.CharField(max_length=1,choices=PAYMENT_TYPE_CHOICES)

Here goes the output when I test it in terminal:

>>> from payment_sys.models import *

>>> payments = [Payment(led_gu5_3_price = 0, led_gu10_price=0,cfl_bc_price = 0, cfl_es_price=0,cfl_sbc_price = 0,cfl_ses_price = 0,initial = 0,payment_type ='E') for i in xrange(3)]

>>> payments

[<Payment: 140801ZKGI 2014-08-01 16:32:36.158811+00:00 Electrician P>, <Payment: 140801ZKGI 2014-08-01 16:32:36.158811+00:00 Electrician P>, <Payment: 140801ZKGI 2014-08-01 16:32:36.158811+00:00 Electrician P>]

As can be seen, time are the same, and the random strings are the same as well. I want the utc_now() and random_string(4) to be executed every time when I create a new Payment object.

网友答案:

You need to use a callable, not a value.

def default_payment_id():
    return utc_now().strftime('%y%m%d')+random_string(4)

payment_id = models.CharField(max_length=10,default=default_payment_id)

Note the lack of calling parentheses in the default: this way Django knows to call it on instantiation, not at import time.

分享给朋友:
您可能感兴趣的文章:
随机阅读: