Home > Software design >  django how to save data to multiple tables
django how to save data to multiple tables

Time:09-06

I have PostgreSQL function that saves data in both items and items_transactionlog, I deleted some rows so its easier to read.

    INSERT INTO public.items
    (remarks,resolution,record_date,resolve)
    VALUES (f_remarks,f_resolution,now(),false);

    INSERT INTO public.items_transactionlog (trans_desc,trans_recorded)
    VALUES ('Add Clearance Item',now());

I want to use this function thru my models.py, Is it possbile to customize my models.py so whenever I save an item it also saves on transactionlog

I use inspectdb and add the following models on my app

class Items(models.Model):
itemid = models.CharField(primary_key=True, max_length=20)
remarks = models.TextField(blank=True, null=True)
resolution = models.TextField(blank=True, null=True)
resolve = models.BooleanField(blank=True, null=True)
resolve_date = models.DateField(blank=True, null=True)
resolve_by = models.CharField(max_length=8, blank=True, null=True)
recorded_by = models.CharField(max_length=8, blank=True, null=True)
record_date = models.DateField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'items'

class ItemsTransactionLog(models.Model):
log_id = models.AutoField(primary_key=True)
trans_desc = models.TextField(blank=True, null=True)
trans_recorded = models.DateField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'items_transactionlog'

CodePudding user response:

Sure, you can override the save() function of your model so it creates a log each time it saves. You can add conditional logic if you don't want a new log item each time (eg if you want it only on the first save you could check for the existance of self.id)

#import the timezone utils for now()
from django.utils import timezone

class Items(models.Model):
...

    class Meta:
        managed = False
    def save():
        """Override the default save to create transaction log"""
        ItemsTransactions.objects.create(
            trans_desc = "Your description",
            trans_recorded = timezone.now()
       )
       #now do the actual saving
       super(Items, self).save(*args, **kwargs)
  • Related