對django 2.x版本中models.ForeignKey()外鍵說明介紹
下面是代碼
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)。
相關(guān)文章:
1. python實現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. php5.6不能擴展redis.so的解決方法3. Java 基于UDP協(xié)議實現(xiàn)消息發(fā)送4. python 爬取嗶哩嗶哩up主信息和投稿視頻5. PHP獲取時間戳等相關(guān)函數(shù)匯總6. Python編寫nmap掃描工具7. 關(guān)于HTML5的img標簽8. python 如何停止一個死循環(huán)的線程9. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值10. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效
