Django學習手冊 - ORM 外鍵
阿新 • • 發佈:2018-08-25
col 表格 pre eat -- test djang plist phy
Django 外鍵操作
關鍵語法:
models.ForeignKey("UserGroup",to_field="gid",default=1,on_delete=models.CASCADE)
參數:
"UserGroup" #外鍵另外一張表
to_field="gid" #另外一張表的字段
on_delete=models.CASCADE #因為不加這個會報錯相關(https://www.cnblogs.com/phyger/p/8035253.html)
創建數據表格:
from django.db import models# Create your models here. class userinfo(models.Model): uname = models.CharField(max_length=32,db_column="用戶名") pwd = models.CharField(max_length=32,db_column="密碼") email = models.EmailField(null=True,db_column="郵箱") usergroup = models.ForeignKey("UserGroup",to_field="gid",default=1,on_delete=models.CASCADE)class UserGroup(models.Model): gid = models.AutoField(primary_key=True) gname = models.CharField(max_length=32) test = models.CharField(max_length=32,null=True) g = models.ForeignKey("Group", to_field="id",null=True,on_delete=models.CASCADE) class Group(models.Model): grouplist= models.CharField(max_length=255)
在每個字段中都錄入數據:
usergroup表 外鍵 g_id
userinfo表 外鍵 usergroup_id
跨表查詢:原理--(對象(對象(對象)))
obj2 = models.userinfo.objects.filter(uname="root").first() print(obj2.usergroup.g.grouplist)
Django學習手冊 - ORM 外鍵