禁令的管理员引用自己

禁令的管理员引用自己

本文介绍了如何让 ForeignKey('self') 禁令的管理员引用自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它自己有一把伪造的钥匙.例如:

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)

出于我的目的,我从不希望 parent_folder 引用自己,但此模型的默认管理界面确实允许用户选择自己的实例.我怎样才能阻止这种情况发生?

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?

如果您像我一样尝试进行分层树布局,那么您需要注意的另一件事是循环父关系.(例如,A 的父级是 B,B 的父级是 C,C 的父级是 A.)避免这不是这个问题的一部分,但我想我会提到它作为提示.

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)

这篇关于如何让 ForeignKey('self') 禁令的管理员引用自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:48