[Django]-Django: Store Hierarchical Data

0👍

objects do not have an id until you save them in Django ORM.

So I’d say you need to save() the object, then reference it in your parent/child sections (and re-save the sections).

However, another option to storing prec and next as pointers is to store an sequence_index (spaced by 10 to allow further inserts wiothout reordering) and order by this index.

0👍

Try doing a save() on all the objects, then update their relations, and then save() all of them again.

When you assign a foreignkey, the related (target) object’s id is copied. since at the moment of assigning the relations (parent_section, predecessor_section) the related objects don’t have an id yet, you get a funky result:

A = Section(name='A')
B = Section(name='B')
B.parent_section = A
A.save() 
B.save()
B.parent_section # this will say A
B.parent_section_id # this will say **None**

But this should work:

A = Section(name='A')
B = Section(name='B')
A.save() 
B.save()
B.parent_section = A
B.parent_section # this will say A
B.parent_section_id # this will say A.id
B.save() # don't forget this one :)

Leave a comment