django-orm 触发器。

# models.py
from django.db.models.signals import pre_save, pre_delete
from django.dispatch import receiver
from django.db import models


class Book(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=150)

@receiver(pre_save, sender=Book)
def pre_save_routers(sender, instance, **kwargs):
    print('sender:', sender)
    print('kwargs:', kwargs)
    if instance.name == '':
        instance.name = '默认名字'
    else:
        instance.name = '默认名字'


@receiver(pre_delete, sender=Book)
def pre_save_routers(sender, instance, **kwargs):
    """
    删除之前
    """
    print('sender:', sender)
    print('kwargs:', kwargs)
posted @ 2021-10-08 11:30  做个笔记  阅读(336)  评论(0编辑  收藏  举报