【问题标题】:Need Contrains for Foreign Key需要外键约束
【发布时间】:2021-02-10 02:56:03
【问题描述】:

我正在用 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 外键。这就是我添加相关名称的原因。 (这是正确的方法吗?)

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

]1

我只想在角色是员工时才显示用户。有可能吗?

【问题讨论】:

    标签: python sql django django-models django-orm


    【解决方案1】:

    是的,您可以使用 limit_choices_to=… parameter [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=… parameter [Django-doc]reverse 中关系的名称。因此,这是一种访问所有具有instructor/examinar 用户的Course 对象的方法。因此,您可能希望将字段重命名为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2017-04-20
      相关资源
      最近更新 更多