如何在Django中阻止同一表中外键的同一对象引用?

2024-05-05 21:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型有一个自外键。你知道吗

型号.py

class Employee(AbstractUser):
    manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name=_('manger'), null=True)

现在,当我将此模型添加到管理站点并尝试更新员工的时,用户可以将自己设置为自己的经理。因此,如果我试图更新员工ID#1,我不希望员工ID#1显示在“经理”下拉列表中。你知道吗

附加问题

我知道我可以在我的更新表单中添加clean方法来验证这个条件,但是我不知道如何获取当前对象ID来检查管理器ID

表单.py

class EmployeeChangeForm(UserChangeForm):

   class Meta:
        model = Employee
        fields = '__all__'

   def clean_manager(self):
        # An Employee Cannot have himself assigned as a manager

        eID = ??  # how do i get the id of Current Employee here ?
        mgr = self.cleaned_data["manager"]
        if eID == mgr:
           raise forms.ValidationError("Employee and Manger should be diffrent !!")
        return mgr

上述方法不允许当前用户阻止员工将自己设置为其经理,但是,该员工仍将显示在“经理”字段的下拉列表中。如果当前员工根本不显示在下拉列表中,我会更喜欢。你知道吗

有办法吗?你知道吗

更新:

我刚刚了解了ForeignKey.limit_choices_to,它将选择限制为相关表中的分词集。但是,我也不知道如何将当前用户id传递给集合。你知道吗

例如:

型号.py

from django.db.models import Q

class Employee(AbstractUser):
    manager = models.ForeignKey(
      'self',
      on_delete=models.SET_NULL,
      related_name=_('manger'),
      null=True,
      limit_choices_to=~Q(id=3),
)

以上代码将我的管理器选项限制为除3之外的所有管理器。但我不知道如何使这个valie充满活力。你知道吗

我不能做limit_choices_to=~Q(id=self.pk)limit_choices_to=~Q(id=self.id)

请帮忙


Tags: to用户pyselfidmodels员工employee
1条回答
网友
1楼 · 发布于 2024-05-05 21:20:40

试试这个:

class EmployeeChangeForm(UserChangeForm):

    class Meta:
        model = Employee
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['manager'].queryset = Employee.objects.exclude(
                pk=self.instance.pk,
            )

别忘了在ModelAdmin中添加form = EmployeeChangeForm来使用表单。你知道吗

相关问题 更多 >