NoteID(PK) NoteText ParentNoteID
1 x -
2 y 1
3 z -
4 a 2
5 b -
6 z 4
如何获取所有记录相关的密钥
恩。得到NiteID 4比结果应该是1,2.4,6所有id或所有对象过滤器。
这可以是您的模型类
class Note(models.Model):
note_text = models.CharField(max_length=255)
parent_id = models.ForeignKey('self', models.DO_NOTHING)
那么函数可以是这样的:
def recursive(note, child_list):
note_children = Note.objects.filter(parent=note)
child_list.append(note.id)
if note_children.count()==0:
return child_list
for n in note_children:
recursive(n, child_list)
return child_list