如何在 Django 中获取所有与 parent 和 child 相关的记录?
How to get all record related parent and child in Django?
NoteID(PK) NoteText ParentNoteID
1 x -
2 y 1
3 z -
4 a 2
5 b -
6 z 4
如何获取所有记录相关的key
例如。得到 NiteID 4 比结果应该是 1,2.4,6 所有 id 或所有 object filter.
这可以是你的模特class
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
NoteID(PK) NoteText ParentNoteID
1 x -
2 y 1
3 z -
4 a 2
5 b -
6 z 4
如何获取所有记录相关的key
例如。得到 NiteID 4 比结果应该是 1,2.4,6 所有 id 或所有 object filter.
这可以是你的模特class
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