Create helper methods for iterating through the parents (like in [wiki:CookBookCategoryDataModel A "category" data model] but I made it more general to avoid code duplication):

30

{{{

31

def foo_recurse_list(obj, parent_field, value_field):

32

parent_list = []

33

try:

34

if getattr(obj, 'parent_'+parent_field+'_id'):

35

p = getattr(obj, 'get_parent_'+parent_field)()

36

if value_field:

37

f = getattr(p, value_field)

38

parent_list.append(f)

39

else:

40

parent_list.append(p)

41

more = recurse_list(p, parent_field, value_field)

42

parent_list.extend(more)

43

finally:

44

return parent_list

45

46

def recurse_list(obj, parent_field, value_field):

47

parent_list = foo_recurse_list(obj, parent_field, value_field)

48

parent_list.reverse()

49

return parent_list

50

}}}

51

52

In your model you will have a foreign key pointing to the parent element of each element and a character field that will be used to store the structure (called "cache_hierarchy" in my code). Then add a _pre_commit handler like this:

53

{{{

54

def _pre_commit(self, opts, cursor):

55

# TODO: import above and remove this import line when django gets the no-magic patches