首页 > 其他分享 >django数据模型db_constraint的使用详解

django数据模型db_constraint的使用详解

时间:2022-12-16 16:11:40浏览次数:50  
标签:SET constraint models db 字段 True 数据模型

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()

through

如果只写manytomany,那么第三张是Django替我们建的,可以通过book.authors字段进行一系列操作(add(增),all(查),set(重置),remove(删除)),但是此时没法给第三张表加其他我们需要的字段,而如果不写,ManyToMany字段,那么我们可以通过Score来执行一些操作,但是此时book和author表已经没有直接的联系了,查询起来很繁琐,有了authors=models.ManyToMany('Author',through='Score'),那么就既可以方便查,也方便业务,添加需要的字段

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 一定要置空,这样删了不会影响其他关联的表

建表时其他参数的设置

CASCADE:这就是默认的选项,级联删除,你无需显性指定它。

PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。

SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。

SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。

SET(): 自定义一个值,该值当然只能是对应的实体了

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),
  )

标签:SET,constraint,models,db,字段,True,数据模型
From: https://www.cnblogs.com/zxr1002/p/16987638.html

相关文章