Django: Store hierarchical data

I am trying to save sections of a document in a Django application. The model is as follows:

class Section(models.Model): project = models.ForeignKey(Project) parent_section = models.ForeignKey('Section', blank=True, null=True, related_name='child_set') predecessor_section = models.ForeignKey('Section', blank=True, null=True, related_name='predecessor_set') name = models.CharField(max_length=100) text = models.TextField(blank=True, null=True) 

I create many sections, bind them (parent_section, predecessor_section) and save them, calling each of my save methods. However, when I look at the table after saving it, parent_section_id and predecessor_section_id are not set, although objects were bound to them before saving.

I assume this is because some parent_section instances do not have an identifier, since their instance has not yet been saved, but using manual transactions cannot solve the problem.

Any thoughts on this?

Cheers, Max

+4
source share
2 answers

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

So, I would say that you need to save () the object and then specify it in the parent / child sections (and re-save the sections).

However, another option for storing prec and next as pointers is to save sequence_index (10 times to allow further inserts without reordering) and sort by that index.

0
source

Try making save () objects on all , then update their relationships, and then save () all of them again.

When assigning a foreign key, the associated (target) identifier of the object is copied. since at the moment of assigning relations (parent_section, predecessor_section) related objects do not yet have an identifier, you get a funny 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 :) 
0
source

All Articles