需要限制外键

时间:2020-10-27 18:47:58

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

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

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

enter image description here] 1

我只想显示角色为职员的用户。有可能吗?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用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 中关系的名称。因此,这是一种访问具有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'}
    )