django数据模型中关于on_delete,db_constraint的参数说明

django数据模型中关于on_delete,db_constraint的参数说明

1.设置为null

class BookModel(models.Model):
    """
    图书
    """
    book_name = models.CharField(max_length=100, verbose_name='书名')
    # 表示外键关联到作者表,当作者表删除了该条数据,图书表中不删除,仅仅是把外键置空
    author = models.ForeignKey(AuthModel, null=True, blank=True, on_delete=models.SET_NULL)
    price = models.FloatField(verbose_name='价格')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

2.建表时其他参数的设置

CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
SET(): 自定义一个值,该值当然只能是对应的实体了

on_delete=None,        # 删除关联表中的数据时,当前表与其关联的field的行为
on_delete=models.CASCADE,   # 删除关联数据,与之关联也删除
on_delete=models.DO_NOTHING, # 删除关联数据,什么也不做
on_delete=models.PROTECT,   # 删除关联数据,引发错误ProtectedError
# models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL,  # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理)
# models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值')
on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理)
on_delete=models.SET,     # 删除关联数据,
 a. 与之关联的值设置为指定值,设置:models.SET(值)
 b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

3.set的使用

def get_sentinel_user():
    return get_user_model().objects.get_or_create(username='deleted')[0]

class MyModel(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET(get_sentinel_user),
    )

4.ManyToMany参数(through,db_constraint)

class Book(models.Model):
    name=models.CharField(max_length=20)
    authors=models.ManyToMany('Author',through='Score')


class Author(models.Model):
    name=models.CharField(max_length=20)


class Score(models.Model):
    book=models.ForeignKey('Book')
    author=models.ForeignKey('Author')
    socre=models.IntegerField()
    
#######
如果只写manytomany,那么第三张是Django替我们建的,可以通过book.authors字段进行一系列操作(add(增),all(查),set(重置),remove(删除)),但是此时没法给第三张表加其他我们需要的字段,

而如果不写,ManyToMany字段,那么我们可以通过Score来执行一些操作,但是此时book和author表已经没有直接的联系了,查询起来很繁琐

有了authors=models.ManyToMany('Author',through='Score'),那么就既可以方便查,也方便业务,添加需要的字段

5.db_constraint

db_constraint=False,这个就是保留跨表查询的便利(双下划线跨表查询```),但是不用约束字段了,一半公司都用false,这样就省的报错,因为没有了约束(Field字段对象,既约束,又建立表与表之间的关系)

limit_choices_to
限制关联字段的对象范围

related_name
反向查询字段可以不用 表名小写,可以改名了

db_table
第三张表的名字


 models.ForeignKey(AuthModel, null=True, blank=True, on_delete=models.SET_NULL,db_constraint=False)

总结

如果使用两个表之间存在关联,首先db_constraint=False 把关联切断,但保留链表查询的功能,其次要设置null=True, blank=True,注意on_delete=models.SET_NULL 一定要置空,这样删了不会影响其他关联的表
posted @ 2022-10-08 10:46  春游去动物园  阅读(28)  评论(0编辑  收藏  举报