亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要外鍵約束

需要外鍵約束

炎炎設計 2024-01-15 17:13:35
我正在 Django 中創建一個大學管理應用程序。這是我的模型。文件:accounts/model.pyfrom django.db import modelsfrom django.contrib.auth.models import AbstractUserclass CustomUser(AbstractUser):    ROLE = {('student', 'student'),            ('staff', 'staff'),            ('account_manager', 'account_manager'),            ('Admin', 'Admin')}    role = models.CharField(choices=ROLE, default='student',                            max_length=20, blank=True, null=True)我正在為所有用戶(員工、學生、HOD 和校長)使用內置用戶類。我們可以通過角色來識別用戶。不,我想創建一個課程數據庫,其中 Staff_id 將是CustomUser表的外鍵。有什么方法可以選擇具有外鍵角色的用戶嗎?class Course(models.Model):    course = models.CharField(max_length=150)    start_date = models.DateField()    end_date = models.DateField()    instructor = models.ForeignKey(        CustomUser, on_delete=models.CASCADE, related_name='instructor_name')    examinar = models.ForeignKey(        CustomUser, on_delete=models.CASCADE, related_name='examinar_name')    def __str__(self):        return f'{self.course.name} Batch No: {self.batch_no}'這里兩者都指的是同一個CustomUser外鍵。這就是為什么我添加了相關名稱。(這是正確的做法嗎?)但在管理頁面上,如果我想添加新課程,我將獲得所有用戶。像這樣:]1我只想在角色是員工時顯示用戶。是否可以?
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

limit_choices_to=…是的,您可以使用參數 [Django-doc]過濾此內容:

class Course(models.Model):

? ? course = models.CharField(max_length=150)

? ? start_date = models.DateField()

? ? end_date = models.DateField()

? ? instructor = models.ForeignKey(

? ? ? ? CustomUser,

? ? ? ? on_delete=models.CASCADE,

? ? ? ? related_name='instructor_name',

? ? ? ? limit_choices_to={'role': 'staff'}

? ? )

? ? examinar = models.ForeignKey(

? ? ? ? CustomUser,

? ? ? ? on_delete=models.CASCADE,

? ? ? ? related_name='examinar_name',

? ? ? ? limit_choices_to={'role': 'student'}

? ? )

然而,參數related_name=…[Django-doc]是反向關系的名稱。因此,這是一種訪問Course具有instructor/examinar用戶身份的所有對象的方法。因此,您可能希望將這些字段重命名為:

class Course(models.Model):

? ? course = models.CharField(max_length=150)

? ? start_date = models.DateField()

? ? end_date = models.DateField()

? ? instructor = models.ForeignKey(

? ? ? ? CustomUser,

? ? ? ? on_delete=models.CASCADE,

? ? ? ? related_name='taught_courses',

? ? ? ? limit_choices_to={'role': 'staff'}

? ? )

? ? examinar = models.ForeignKey(

? ? ? ? CustomUser,

? ? ? ? on_delete=models.CASCADE,

? ? ? ? related_name='followed_courses',

? ? ? ? limit_choices_to={'role': 'student'}

? ? )


查看完整回答
反對 回復 2024-01-15
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號