我根据UTC时间生成了payment_id,并附加了4个随机字符。但是当我调用该函数时,utc_now()和random_string(4)似乎只执行了一次。
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)
当我在终端中测试它时输出:
>>> 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>]
可以看出,时间是一样的,随机字符串也是一样的。我希望每次创建新的Payment对象时都执行utc_now()和random_string(4)。
答案 0 :(得分:0)
您需要使用可调用值,而不是值。
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)
请注意默认情况下缺少调用括号:这样Django知道在实例化时调用它,而不是在导入时调用它。