简体   繁体   English

django模型中如何创建基于其他表的触发器更新字段

[英]How to create trigger update fields based on other table in django models

I have two models, In activity model status is column name this column row has to update from 'Pending' to 'Done', when status column row update from 'Pending' to 'Done' in Item model.It has to update automatically when db field get change.我有两个模型,在活动 model 中,状态是列名,当项目 model 中的状态列行从“待定”更新为“完成”时,该列行必须从“待定”更新为“完成”。它必须自动更新时数据库字段得到改变。

class Activity(models.Model):
   a_id = models.AutoField(primary=True, unique=True)
   status = models.CharField(max_length=225, blank=True,null=True, default="Pending")
class Item(models.Model):
   item_id = models.AutoField(primary=True, uniue=True)
   status = models.CharField(max_length=225, blank=True, null=True, default="Pending")
   activityid = models.ForeginKey(Activity, on_delete=models.CASCADE, 
                                           related_name="activitynt")

In models.py use signals to update your status在 models.py 中使用信号来更新你的状态

models.py模型.py
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Activity)
def update_item_status(sender, instance,created, **kwargs):
    Item.objects.filter(activityid=instance.pk).update(status=instance.status)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM