Traversing nested models is a mess. (or i don't get it right)

417 views
Skip to first unread message

Adrian Scheffler

unread,
May 22, 2014, 1:53:48 PM5/22/14
to django...@googlegroups.com
Hi there.
supposed you've got a nested model like this:
class Article(models.Model):

    parent_article = models.OneToOneField("self", blank=True, null=True, default=None, related_name="child_article")

How would you traverse the related model chain ( aka linked list ) to one end?
Maybe with a generator that makes you a nice list, that can be printed:
def article_child_gen(article):
    yield article.child_article
    while True:
        yield from article_child_gen(article.child_article)
This throws an exception if it reaches the end. You catch it and return. Great. In theory. The problem is that its not easy to catch it, because you are not allowed to catch it.
It's name is RelatedObjectDoesNotExist, defined by SingleRelatedObjectDescriptor in django.db.models.fields.related . So my question is: is there a way to catch this anyway, or to get around it? Because the other path that i am going now is to Article.objects.filter(parent_article=blabla) me through this problem. But this just doesn't seem to be a clean solution.
thanks!

Adrian Scheffler

unread,
May 22, 2014, 3:30:39 PM5/22/14
to django...@googlegroups.com
Okay, got it (at least i hope so :-) ):
def article_child_gen(article):
    while True:
        try:
            article = Article.objects.get(parent_article=article)
            yield article
        except Article.DoesNotExist:
            return
Reply all
Reply to author
Forward
0 new messages