如何使外号(“自”)的管理员禁止引用自身? [英] How can make the admin for a ForeignKey('self') ban referring to itself?

查看:139
本文介绍了如何使外号(“自”)的管理员禁止引用自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有伪装密钥的模型。例如:

 类文件夹(models.Model):
name = models.CharField()
parent_folder = models.ForeignKey('self',null = True,blank = True,default = None,on_delete = models.CASCADE)

为了我的目的,我不希望 parent_folder 引用自己,但是该模型的默认管理界面允许用户选择自己的实例。如何阻止这种情况发生?



编辑:如果您正在尝试分层树状布局,就像我一样,另一件事你需要注意是圆形的父母关系。 (例如,A的父母是B,B的父母是C,C的父母是A.)避免这不是这个问题的一部分,但我以为我会提到它作为一个提示。

解决方案

我会亲自在模型级别执行此操作,所以如果您以另一种形式重用该模型,您也会收到错误:

 类文件夹(models.Model):
name = models.CharField()
parent_folder = models.ForeignKey('self' ,null = True,blank = True,default = None,on_delete = models.CASCADE)

def clean(self):
if self.parent_folder == self:
raise ValidationError(一个文件夹不能是其自己的父)

如果您在形式,使用查询,所以模型本身不会出现:

  class FolderForm(forms.ModelForm):

class Meta:
model =文件夹
fields =('name','parent_folder')

def __init __(self,* args,** kwargs):
super(FolderForm,self).__ init __(* args,** kwargs)
如果hasattr(self,'instance')和hasattr(self .instance,'id'):
self.fields ['parent_folder']。queryset = Folder.objects.exclude(id = self.instance.id)


I have a model with a forgein key to itself. For example:

class Folder(models.Model):
    name = models.CharField()
    parent_folder = models.ForeignKey('self', null=True, blank=True, default=None, on_delete=models.CASCADE)

For my purposes, I never want parent_folder to refer to itself, but the default admin interface for this model does allow the user to choose its own instance. How can I stop that from happening?

Edit: If you're trying to do a hierarchical tree layout, like I was, another thing you need to watch out for is circular parent relationships. (For example, A's parent is B, B's parent is C, and C's parent is A.) Avoiding that is not part of this question, but I thought I would mention it as a tip.

解决方案

I would personally do it at the model level, so if you reuse the model in another form, you would get an error as well:

class Folder(models.Model):
    name = models.CharField()
    parent_folder = models.ForeignKey('self', null=True, blank=True, default=None, on_delete=models.CASCADE)

    def clean(self):
        if self.parent_folder == self:
            raise ValidationError("A folder can't be its own parent")

If you use this model in a form, use a queryset so the model itself doesn't appear:

class FolderForm(forms.ModelForm):

    class Meta:
        model = Folder
        fields = ('name','parent_folder')

    def __init__(self, *args, **kwargs):
        super(FolderForm, self).__init__(*args, **kwargs)
        if hasattr(self, 'instance') and hasattr(self.instance, 'id'):
            self.fields['parent_folder'].queryset = Folder.objects.exclude(id=self.instance.id)

这篇关于如何使外号(“自”)的管理员禁止引用自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆