需要外键约束

我正在 Django 中创建一个大学管理应用程序。


这是我的模型。文件:accounts/model.py


from django.db import models

from django.contrib.auth.models import AbstractUser


class 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外键。这就是为什么我添加了相关名称。(这是正确的做法吗?)


但在管理页面上,如果我想添加新课程,我将获得所有用户。像这样:

https://img1.sycdn.imooc.com/65a4f75400011c4704730306.jpg

]1

我只想在角色是员工时显示用户。是否可以?


炎炎设计
浏览 41回答 1
1回答

杨__羊羊

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'}    )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python