开发者

How to get field with ForeignKey('self') without the possibility to link to same entry?

I came in touch with a little problem while building a model with a foreign key to itself.

Here an example:

class Example (model.Model):
    parent = models.ForeignKey('self', null=True, blank=True)
    # and some other fields

After creating a new entry in the admin panel开发者_JS百科 and going into this example for editing some content, I realize that I could set the parent to the current entry. But thats not what I wanted to get with the ForeignKey and the relation to itself.

Is it possible to disallow the link to itself?

Maybe it's better to use a integer field with the right choices but I'm not quiet sure how to realize this an a smooth and Python like way.


one way to do this would be to override the model's clean method

class Example(model.Model):
    #...
    def clean(self):
        if self.parent.id == self.id:
            raise ValidationError("no self referential models")

this will be called as the second step of object validation and will prevent the object from being inserted in the database.


It is possible to disallow a link from an instance to the same instance. One way to achieve this would be to add a custom model validation. For e.g.

class Example(models.Model):
    ...
    def clean_fields(self):
        if self.id and self.parent.id == self.id:
            raise ValidationError(...)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜