[Answered ]-Best practice for accessing distantly related Django models

2👍

✅

Use Properties

My current approach would be to add a property to the Ten model, abstracting away that attribute chaining:

class Ten(models.Model):
    nine = models.ForeignKey(Nine)

    @property
    def one(self):
        return self.nine.eight.seven.six.five.four.three.two.one

I can see a downside to this tactic however, and that’s the added mysticism involved. Does the Ten instance actually have a relation to the One model or not? I wouldn’t be able to tell without inspecting the model myself.

0👍

You probably want to use django-mptt for sophisticated hierarchal models although it can be a bit ott. If you want a simple hierarchy then add a ForeignKey to self:

class Number(models.Model):
    parent = models.ForeignKey('self', blank=True, null=True,
        related_name='child')

then the query would be something like this based on a unique field, say slug:

Number.objects.get(parent__slug='one')

Leave a comment