skinnyas123
skinnyas123

Reputation: 382

django: auto insert rows into database

I have a table for CUSTOMER and a table for CUSTOMER_PAYMENT (w/ attributes customer, amount, date due and paid) . I want when I insert a value in CUSTOMER, values in CUSTOMER_PAYMENT will be automatically generated. It's like a monthly billing information

Upon inserting customer A in CUSTOMER

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

How is that done?

There is no trigger in Django. I tried to Google but I can't find how.

Upvotes: 1

Views: 1574

Answers (2)

dani herrera
dani herrera

Reputation: 51745

There are two ways:

  • write code in post_save signal
  • overwrite save() method

Signals:

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()

Overwriting:

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()

Upvotes: 1

tback
tback

Reputation: 11571

Post Save Signals might be the thing you're searching for

Upvotes: 0

Related Questions