关于django 2.x版本中models.ForeignKey() 外键说明

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanglei_storage/article/details/84037315

下面是代码

class GroupInfos(models.Model):
    uid = models.AutoField(primary_key=True)
    caption = models.CharField(max_length=32, unique=True)
    ctime = models.DateTimeField(auto_now_add=True, null=True)
    uptime = models.DateTimeField(auto_now=True, null=True)

class UserInfos(models.Model):
    username = models.CharField(max_length=32, blank=True, verbose_name='用户名')
    password = models.CharField(max_length=64, help_text='text')
    email = models.EmailField(max_length=60)
    user_group = models.ForeignKey('GroupInfos', to_field='uid', on_delete='CASCADE')


说明

第一个class创建一个名称为app_groupinfos的表
第二个class创建一个名称为app_userinfos的表

1、ForeignKey 表示设置外健
2、to_field表示外健关联的主键
3、on_delete有多个选项

引用 https://www.cnblogs.com/phyger/p/8035253.html:
在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:
TypeError: init() missing 1 required positional argument: ‘on_delete’
举例说明:
user=models.OneToOneField(User)
owner=models.ForeignKey(UserProfile)
需要改成:
user=models.OneToOneField(User,on_delete=models.CASCADE) --在老版本这个参数(models.CASCADE)是默认值
owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE) --在老版本这个参数(models.CASCADE)是默认值
参数说明:
on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个可选择的值
CASCADE:此值设置,是级联删除。
PROTECT:此值设置,是会报完整性错误。
SET_NULL:此值设置,会把外键设置为null,前提是允许为null。
SET_DEFAULT:此值设置,会把设置为外键的默认值。
SET():此值设置,会调用外面的值,可以是一个函数。
一般情况下使用CASCADE就可以了。

那么,这个时候一个group就会对应多个user,属于一对多的类型。
当我们查询一个组有那些用户的时候,就会用到当前的外健,

创建记录

并且,在class中定义了foreignKey之后,group还不存在的同时,user表也因为约束的原因,不能被进行创建

删除记录

并且,在class中定义了foreignKey之后,user中记录存在的同时,group表中的记录也因为约束的原因,不能被进行删除

猜你喜欢

转载自blog.csdn.net/wanglei_storage/article/details/84037315