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 4 years, 4 months ago
  2. PositionField by jpwatts 3 years, 6 months ago
  3. ThumbnailMixIn by johan 2 years, 10 months ago
  4. Custom model field to store dict object in database by rudyryk 1 year, 10 months ago
  5. Foreign Key list_filter wthout custom FilterSpec by haileris23 2 years ago

Comments

(Forgotten your password?)