SelfForeignKey to prevent hierarchical loops

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class SelfForeignKey(models.ForeignKey):
    def pre_save(self, instance, add):
        manager = instance.__class__.objects
        ancestor_id = getattr(instance, self.attname)
        while ancestor_id is not None:
            if ancestor_id == instance.id:
                return None
            ancestor = manager.get(id=ancestor_id)
            ancestor_id = getattr(ancestor, self.attname)
        return getattr(instance, self.attname)

# used like this:

class Category(models.Model):
    name = models.CharField(max_length=20)
    parent = SelfForeignKey('self', related_name='child_category_set', ...)

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.