[英]How to block same object reference for Foreign key in same table in Django?
我有一個具有自我外鍵的模型。
models.py
class Employee(AbstractUser):
manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name=_('manger'), null=True)
現在,當我將此模型添加到管理站點並嘗試更新員工時,用戶可以將他們自己設置為自己的經理。 因此,如果我要更新員工ID#1,我不希望在管理器下拉列表中顯示員工ID#1。
附加問題
我知道我可以在“更新”表單中添加驗證此條件的干凈方法,但是我不知道如何獲取當前對象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之外的所有經理。但是我不知道如何使這種優勢成為動態。
我不能做limit_choices_to=~Q(id=self.pk)
或limit_choices_to=~Q(id=self.id)
請幫忙
嘗試這個:
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,
)
不要忘記通過添加form = EmployeeChangeForm
在ModelAdmin
使用該表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.