django:自动将行插入数据库

时间:2012-09-17 07:29:37

标签: mysql sql django

我有一个CUSTOMER表和一个CUSTOMER_PAYMENT表(包含客户,金额,到期日期和付款)。我想在CUSTOMER中插入一个值时,将自动生成CUSTOMER_PAYMENT中的值。这就像是每月结算信息

在CUSTOMER中插入客户A

CUSTOMER_PAYMENT
____________________________________
|CUSTOMER|AMOUNT|     DUE   | PAID  |
|  A     | 100  | 2011-01-15| False |
|  A     | 100  | 2011-02-15| False |
|  A     | 100  | 2011-03-15| False |

这是怎么做到的?

Django没有触发器。我试过谷歌,但我找不到。

2 个答案:

答案 0 :(得分:1)

两种方式

  • 在post_save信号中编写代码
  • 覆盖save()方法

<强>信号

post_save.connect(CUSTOMER_post_save, sender = CUSTOMER , 
                 instance = instance, create = create) 

def CUSTOMER_post_save(sender, instance, **kwargs):
        if create:
            cd = CUSTOMER_PAYMENT()
            cd.amount = ....
            cd.save()

<强>覆写

class CUSTOMER(model.Model):
    ...    
    def save(self, *args, **kwargs):
        is_new = self.pk is None
        super(yourModel, self).save(*args, **kwargs)
        if is_new:
            cd = CUSTOMER_PAYMENT()
            cd.amount = ....
            cd.save()

答案 1 :(得分:0)

Post Save Signals可能是您正在搜索的内容