【问题标题】:How to get all record related parent and child in Django?如何在Django中获取所有与记录相关的父母和孩子?
【发布时间】:2019-09-14 19:02:29
【问题描述】:
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 或所有对象过滤器。

【问题讨论】:

  • 你尝试过什么吗?请在此处提供您的代码。
  • 我没有尝试过 Django,目前我正在尝试 DB(MySQL) 级别,但最后,我想通过 Django 来做。
  • select identifier_id, link_identifier_id from (select identifier_id,link_identifier_id from NRS_IDENTIFIER order by link_identifier_id, identifier_id) a , (select @pv := '979') b where find_in_set(link_identifier_id, @pv) and length( @pv := concat(@pv, ',', identifier_id));

标签: python django django-orm


【解决方案1】:

这可以是你的模型类

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 

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多