我有一个模型,它有自己的外键。
models.py
class Employee(AbstractUser):
manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name=_('manger'), null=True)
现在,当我将此模型添加到管理站点并尝试更新员工时,用户可以将自己设置为自己的经理。因此,如果我试图更新员工ID #1,我不希望员工ID #1显示在“经理”下拉列表中。
附加问题
我知道我可以在Update表单中添加验证此条件的clean方法,但是我不知道如何获取当前的对象ID来检查经理ID。
forms.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传递给集合。
例如:
models.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)
请帮帮忙
发布于 2017-12-21 20:16:04
试试这个:
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
中的表单。
https://stackoverflow.com/questions/47790517
复制相似问题