为了账号安全,请及时绑定邮箱和手机立即绑定

需要外键约束

需要外键约束

炎炎设计 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 关注
  • 36 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信