I have a model class 'Organization' with a parent and I do this with a
method get_child_orgs:

get_child_orgs(self):
    child_orgs = []
    co = Organization.objects.filter(parent__exact = self)
    for c in co:
        child_orgs.append(c)
        gc = c.get_child_orgs()
        child_orgs.extend(gc)
    return child_orgs


On 10/8/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>
> Ok..thanks.. I was afraid I was going to get that answer.  If I do
> this with select_related, I'm still going to have to implement a loop
> to display them all in one list, because they'd come back as
> company.parent_company.parent_company etc, instead of all in one top
> level list... right?
>
>
> On Oct 8, 9:19 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
> wrote:
> > On Mon, 2007-10-08 at 13:13 +0000, [EMAIL PROTECTED] wrote:
> > > In my model class I have:
> >
> > > class Company(models.Model):
> > >     company_id = models.AutoField(primary_key=True)
> > >     parent_company = models.ForeignKey("self",null=True)
> > >     .
> > >     .
> >
> > > How would I query to get back all children companies, as well as all
> > > of their children companies, and their children companies, etc,
> > > without writing a nested loop to do so?
> >
> > You can't do it with a general query because there's no way to do it in
> > SQL with this data structure. The SQL has to do a join each time you
> > query from parent back to child (or vice-versa), so we need to know the
> > number of joins to create a query construction time.
> >
> > There is a "depth" parameter for select_related() queries that limits
> > the number of recursion steps (otherwise infinite loops would result for
> > queries like this) and you could use that to control the maximum number
> > of children. However, I believe there are some bugs with it working for
> > small values of depth (depth=1) and there might be others, so check the
> > results carefully.
> >
> > Regards,
> > Malcolm
>
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to