第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

需要外鍵約束

需要外鍵約束

炎炎設(shè)計 2024-01-15 17:13:35
我正在 Django 中創(chuàng)建一個大學(xué)管理應(yīng)用程序。這是我的模型。文件: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)我正在為所有用戶(員工、學(xué)生、HOD 和校長)使用內(nèi)置用戶類。我們可以通過角色來識別用戶。不,我想創(chuàng)建一個課程數(shù)據(jù)庫,其中 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外鍵。這就是為什么我添加了相關(guān)名稱。(這是正確的做法嗎?)但在管理頁面上,如果我想添加新課程,我將獲得所有用戶。像這樣:]1我只想在角色是員工時顯示用戶。是否可以?
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經(jīng)驗 獲得超7個贊

limit_choices_to=…是的,您可以使用參數(shù) [Django-doc]過濾此內(nèi)容:

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'}

? ? )

然而,參數(shù)related_name=…[Django-doc]是反向關(guān)系的名稱。因此,這是一種訪問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'}

? ? )


查看完整回答
反對 回復(fù) 2024-01-15
  • 1 回答
  • 0 關(guān)注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號