2011-11-03 57 views
0

以下是我在模型中的一种保存方法。django自定义保存方法问题与新创建的对象ID

我试图使用新创建的id当对象被保存到填充另一个字段,如第73行所示。这可能不会很好,因为该对象尚未创建。

做什么,我试图达到什么最好的方式?我应该将超级方法移到哪里?

64  def save(self, *args, **kwargs): 
65   ''' 
66   Save invoice and receipt number 
67   ''' 
68   
69   if self.status == 'pending' and self.invoice is None: 
71    invoice = "%s-Inv-%s-%s" % (self.event.event_acronym, 
72           date.today().strftime('%y%m%d'), 
73           self.id) 
74    self.invoice = invoice 
75    super(Order, self).save(*args, **kwargs) 
76 
77   if self.status == 'completed' and self.receipt is None: 
78    total_success = Order.objects.all.filter(status='completed').count() 
79    if not total_success: 
80     receipt = "%s-R-%s-%s" % (self.event.acronym, 
81           date.today().strftime('%y%m%d'), 
82           1) 
83    else: 
84     receipt = "%s-R-%s-%s" % (self.event.event_acronym, 
85           date.today().strftime('%y%m%d'), 
86           total_success + 1) 
87    self.receipt = receipt 
88    self.receipt_date = datetime.datetime.now 
89    super(Order, self).save(*args, **kwargs) 

回答

0

如果你想访问保存的对象,你需要运行super ().save()首先 例如,将上述行75移至行前71

虽然它可能值得退后一步,想想你的实际上是试图实现的。如上所述,信号可能是你的朋友在这里

0

你的问题是自我没有一个id,直到其保存的ORM。

if not self.id: 
    # is True the first time an object is saved 

的信号会让你触发一个函数的对象被保存后,所以它有它的ID,你可以去了解您的业务。

相关问题