mohammad
mohammad

Reputation: 2198

Trigger to send new rows added to database to another database in postgres?

I have 2 databases on 2 different servers (say A & B).
I have some crawlers that use API functions to write data to database (A). Some of this data are new and others are just updates to previous rows. If some new rows are added to (A) I want to add id of these new rows to (B).


I want this to happen in real time without full scan of (A) iteratively. I want something like a trigger in (A) to send new ids to (B). How should I do write this trigger?(If you think there is a better solution, please help me)

Upvotes: 0

Views: 360

Answers (1)

Thameem
Thameem

Reputation: 3636

you can do it by using django signals. Signals means just like trigger. if you want do any operation while creating updating deleting models. you can use signals. django reference reference example

suppose you have two models named:

class A(models.Model):
  name = models.CharField(max_length=128)

class B(models.Model):
  a = models.ForeignKey(A)

save this file in your app/signals.py

from django.db.models.signals import post_save
from .models import A,B

def create_b(sender, instance, created, *args, **kwargs):

    if created:
       B.objects.create(a=instance)

post_save.connect(create_b, sender=A)

and inorder to work this signals properly you have to call it in apps config. and in app.py file copy this

class ProductConfig(AppConfig): #this will be different
    name = 'product' # this will be different based on your app name
#copy below lines only
    def ready(self):
        from .signals import *

and in your app's __init__.py file include this line

default_app_config = "product.apps.ProductConfig"

Upvotes: 2

Related Questions