On 12/15/06, leanmeandonothingmachine
<[EMAIL PROTECTED]> wrote:
>
> I have a model where the foreign key refers to it self.
> parent = models.ForeignKey('self', core=True, null=True, blank=True)
>
> What i want to do is to be able to run a query with select_related and
> get all the parents of that row. When I run test =
> content.objects.select_related().get(pk=3) and if I knew how many
> parents there are I can get them all using test.parent then
> test.parent.parent... etc.. But I need to be able to iterate though and
> get the full list. Does anyone how I can do that?

FWIW, one thing I have done when storing trees in sql (particularly in
postgres; I don't know if mysql and/or sqlite support this) is have an
attribute "path" which is the colon-separated list of ids of the
parents. The bit that possibly postgres-dependent is that I then added
a constraint that checked that the path is the empty string if parent
is null, and equal to that of the parent plus the id of the parent
plus a colon otherwise (I could've made it happen automagically with a
stored procedure, but I don't like those things).

The nice thing of having the path in there is that most operations on
the tree that would typically involve a traversal are really trivial,
and keeping the path synchronized is not at all hard. For example, to
check if node A is an ascendant of node B:

  B.path.startswith(A.path)

to pull all the descendants of node A from the database:

  Node.objects.filter(path__startswith=A.path)

the ugly thing is that now your database is denormalized, and your
friends that teach Databases at the university will sneer.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
The trouble with a lot of self-made men is that they worship their creator.

--~--~---------~--~----~------------~-------~--~----~
 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