回到顶部

阅读目录

django Foreignkey 之 on_delete

on_delete 指的是通过 ForeignKey 连接起来的当前对象被删除后,外键字段进行的操作。

# models.py

from django.db import models


class Article(models.Model):
    """
    主题表/文章表
    """
    title = models.CharField(max_length=128, verbose_name="标题")
    content = RichTextUploadingField(verbose_name="内容", config_name='awesome_ckeditor')
    node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, verbose_name="所属节点")  # models.DO_NOTHING, Article 删除 Node 啥也不干

# D:\Program Files\Python36\Lib\site-packages\django\db\models\deletion.py

def CASCADE(collector, field, sub_objs, using):
    """
    当前对象删除后,一并删除该对象下的外键信息
    :param collector:
    :param field:
    :param sub_objs:
    :param using:
    :return:
    """
    collector.collect(sub_objs, source=field.remote_field.model,
                      source_attr=field.name, nullable=field.null)
    if field.null and not connections[using].features.can_defer_constraint_checks:
        collector.add_field_update(field, None, sub_objs)


def PROTECT(collector, field, sub_objs, using):
    """
    删除时会引起 ProtectedError,不删除关联表的内容
    :param collector:
    :param field:
    :param sub_objs:
    :param using:
    :return:
    """
    raise ProtectedError(
        "Cannot delete some instances of model '%s' because they are "
        "referenced through a protected foreign key: '%s.%s'" % (
            field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name
        ),
        sub_objs
    )


def SET(value):
    """
    SET(), 此时需要指定 set 的值, 括号里可以是函数,也可以为自己定义的东西;
    :param value:
    :return:
    """
    if callable(value):
        def set_on_delete(collector, field, sub_objs, using):
            collector.add_field_update(field, value(), sub_objs)
    else:
        def set_on_delete(collector, field, sub_objs, using):
            collector.add_field_update(field, value, sub_objs)
    set_on_delete.deconstruct = lambda: ('django.db.models.SET', (value,), {})
    return set_on_delete


def SET_NULL(collector, field, sub_objs, using):
    """
    只有当当前字段设置 null 设置为 True 才有效,此情况会将 ForeignKey 字段设置为 null
    :param collector:
    :param field:
    :param sub_objs:
    :param using:
    :return:
    """
    collector.add_field_update(field, None, sub_objs)


def SET_DEFAULT(collector, field, sub_objs, using):
    """
    当前字段设置了default 才有效,此情况会将 ForeignKey 字段设置为 default 值
    :param collector:
    :param field:
    :param sub_objs:
    :param using:
    :return:
    """
    collector.add_field_update(field, field.get_default(), sub_objs)


def DO_NOTHING(collector, field, sub_objs, using):
    """
    什么也不做
    :param collector:
    :param field:
    :param sub_objs:
    :param using:
    :return:
    """
    pass

 

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: 个人网站前端模板收集(网站模板)
下一篇: django-haystack 让检索结果开头不缩略显示(完全显示)