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', ...)

More like this

  1. Self-referencing Foreign Key Infinite Loop by minarets 5 years, 8 months ago
  2. Nested set abstraction for hierarchical data by lars.yencken 5 years ago
  3. Foreign Key list_filter wthout custom FilterSpec by haileris23 3 years, 3 months ago
  4. Comma Seprated Character Field to store Geographic Coordinates by vijay.shanker 5 months ago
  5. models.py with django_dag models for parts hierarchy by j_syk 1 year, 9 months ago

Comments

(Forgotten your password?)