[Django]-Modeling hierarchical data in django with polymorphic node types

3πŸ‘

βœ…

I finally found an answer via some great help on IRC here and wanted to share it in case anyone else had the same problem.

The only thing I had to ultimately change was Flow.getChildren().

def getChildren(self):
    # Get a list of all the attrs relating to Child models.
    child_attrs = dict(
        (rel.var_name, rel.get_cache_name())
        for rel in Step._meta.get_all_related_objects()
        if issubclass(rel.field.model, Step) and isinstance(rel.field, models.OneToOneField)
    )

    objs = []
    for obj in self.children.all().select_related(*child_attrs.keys()):
        # Try to find any children...
        for child in child_attrs.values():
            sobj = obj.__dict__.get(child)
            if sobj is not None:
                break
        objs.append(sobj)
    return objs

If anyone has a cleaner solution I’d love to see it, especially since this seems like a lot of work for something it seems like the framework should handle more directly.

πŸ‘€Jorvis

0πŸ‘

The thing that jumps out at me is β€œreturn Step.objects.filter(parent_id=self.parent_id)”. I believe it should be β€œreturn Step.objects.filter(parent__pk=self.parent.pk)”

Leave a comment