What would be the most djangoish way to run through relations until last child?

78 views Asked by At

I'm struggling on finding an efficient way to go through Django m2m relations.

My use is case :

  • I receive a string from a form and update the status of an element with this string.
  • If this element has children, I update their status with the same value.
  • If those children element have themselves children, then I update the status and goes through their children etc ..

My model m2m field is like : parent = models.ManyToManyField('self', blank=True, default=None, symmetrical=False, verbose_name="")

Currently I've written something like this :

if model == Ensemble:
    children = elem.ensemble_set.all()
    for child in children:
        update_elem_statut(child, statut)
        for en in child.ensemble_set.all():
            update_elem_statut(en, statut)
            if len(en.ensemble_set.all()):
                for en_child in en.ensemble_set.all():
                    update_elem_statut(en_child, statut)

But that's definitely not recursive. I would need to loop through every children until there are only children element. I've no idea what would be the most pythonish/djangoish way to do this.

Thanks in advance for any help.

1

There are 1 answers

5
Iain Shelvington On BEST ANSWER

Easy way to do this is to add a method to your model that calls the same method on all of the current objects children

class Ensemble(models.Model):

    def update_status(self, status):
        self.status = status
        self.save()
        for child in self.ensemble_set.all():
            child.update_status(status)