我在2个不同的服务器上有2个数据库(比如A& B)
我有一些使用API函数将数据写入数据库(A)的爬虫。其中一些数据是新数据,其他数据只是对以前行的更新。如果向(A)添加了一些新行,我想将这些新行的id添加到(B)。
我希望这是实时发生的,而不是迭代地完全扫描(A)。我希望像(A)中的触发器一样向(B)发送新的ID。我应该怎么写这个触发器?(如果你认为有更好的解决方案,请帮帮我)
答案 0 :(得分:2)
你可以使用django信号来做到这一点。信号就像触发一样。如果要在创建更新删除模型时执行任何操作。你可以使用信号。 django reference reference example
假设您有两个名为的模型:
class A(models.Model):
name = models.CharField(max_length=128)
class B(models.Model):
a = models.ForeignKey(A)
将此文件保存在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)
为了正确处理此信号,您必须在应用配置中调用它。
并在app.py
文件中复制此
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 *
并在您应用的__init__.py
文件中包含此行
default_app_config = "product.apps.ProductConfig"