回到顶部

CONTENTS

django Foreignkey 之 on_delete

on_delete 指的是通过 ForeignKey 连接起来的对象被删除后,当前字段怎么变化。

# models.py

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="所属节点")

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

def CASCADE(collector, field, sub_objs, using):
    """
    对就对象删除后,包含 ForeignKey 的字段也会被删除
    :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 的值
    :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 让检索的结果不缩略显示