国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

對django 2.x版本中models.ForeignKey()外鍵說明介紹

瀏覽:6日期:2024-10-16 18:24:14

下面是代碼

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創(chuàng)建一個名稱為app_groupinfos的表

第二個class創(chuàng)建一個名稱為app_userinfos的表

1、ForeignKey 表示設(shè)置外健

2、to_field表示外健關(guān)聯(lián)的主鍵

3、on_delete有多個選項

在django2.0后,定義外鍵和一對一關(guān)系的時候需要加on_delete選項,此參數(shù)為了避免兩個表里的數(shù)據(jù)不一致問題,不然會報錯:

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) --在老版本這個參數(shù)(models.CASCADE)是默認值owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE) --在老版本這個參數(shù)(models.CASCADE)是默認值

參數(shù)說明:

on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五個可選擇的值

CASCADE:此值設(shè)置,是級聯(lián)刪除。

PROTECT:此值設(shè)置,是會報完整性錯誤。

SET_NULL:此值設(shè)置,會把外鍵設(shè)置為null,前提是允許為null。

SET_DEFAULT:此值設(shè)置,會把設(shè)置為外鍵的默認值。

SET():此值設(shè)置,會調(diào)用外面的值,可以是一個函數(shù)。

一般情況下使用CASCADE就可以了。

那么,這個時候一個group就會對應(yīng)多個user,屬于一對多的類型。

當我們查詢一個組有那些用戶的時候,就會用到當前的外健,

創(chuàng)建記錄

并且,在class中定義了foreignKey之后,group還不存在的同時,user表也因為約束的原因,不能被進行創(chuàng)建

刪除記錄

并且,在class中定義了foreignKey之后,user中記錄存在的同時,group表中的記錄也因為約束的原因,不能被進行刪除

補充知識:owner = models.ForeignKey(User)出現(xiàn)TypeError

owner = models.ForeignKey(User)出現(xiàn)錯誤 TypeError: init() missing 1 required positional argument: ‘on_delete’owner = models.ForeignKey(User)

出現(xiàn)下列錯誤:

TypeError: __init__() missing 1 required positional argument: ’on_delete’

解決辦法:

owner = models.ForeignKey(User, on_delete=models.CASCADE)

以上這篇對django 2.x版本中models.ForeignKey()外鍵說明介紹就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Django
相關(guān)文章:
主站蜘蛛池模板: 靖宇县| 宜君县| 临猗县| 修水县| 临潭县| 沙洋县| 博兴县| 分宜县| 朔州市| 望城县| 关岭| 岢岚县| 中方县| 兴义市| 卢龙县| 普定县| 碌曲县| 沅陵县| 普兰县| 九江市| 大厂| 陆川县| 莲花县| 桐柏县| 工布江达县| 滨海县| 浏阳市| 彩票| 西丰县| 梅河口市| 河间市| 朝阳县| 玛纳斯县| 高青县| 富平县| 淮滨县| 白银市| 广东省| 永胜县| 庐江县| 榕江县|