Django One to Many Models
在django 的App 中的models 中加上Classroom,Group,UserProfile
在34行中設定UserProfile 與User 存在一對多的關係,在Foreign
執行
python manage.py makemigrations
python manage migrate
目前的models 如下
在資料庫中補上幾筆資料後回來看彼此的關聯
classroom 建立兩筆資料
userprofile 與user 及classroom 的關係如下
在python console 中執行
from django.contrib.auth.models import User
from app1.models import Classroom,Group,UserProfile
user = User.objects.get(id = 1)
傳回結果為 <User: yhlin>
因在models中有 related_name 的關係,在user的物件可用user_profile 來取得
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_profile')
執行
userprofiles = user.user_profile.all()
可取得QuerySet 物件<QuerySet [<UserProfile: yhlin>, <UserProfile: yhlin>]>
利用for each 取的其他欄位
for userprofile in userprofiles:
… print(userprofile.id, userprofile.authority,userprofile.position)
1 S student
2 S student
因在Userprofile 中有設定ManyToMany的關係,
classroom = models.ManyToManyField(Classroom,related_name='userprofile')
在userprofile中可利用取得對應
for userprofile in userprofiles:
… classrooms = userprofile.classroom.all()
… print(classrooms)
<QuerySet [<Classroom: 大雄翻花繩>]>
<QuerySet [<Classroom: 靜香小提琴>]>