构建自引用外键行的层次结构

时间:2017-01-10 17:22:11

标签: python django foreign-keys hierarchy

我有这些模特

def Group(Model):
    parent_group = ForeignKey("self")
    name = CharField(max=12)

def Member(Model):
    group = ForeignKey(Group)
    name = CharField(max=12)
    score = BigIntegerField()

群组可以嵌套任意次。如何编写以下列格式返回数据的函数?

{Group1: {Group2: {Group3: {Group4:{Member2: score}, Member1: score}, Member3:score}}}

我尝试编写以下递归函数,但它不起作用。

rd = {}
def find_parent(group):
    if group.parent_group is not None:
        return find_parent(group.parent_group)
    else:
        return group

def populate_with_groups(parent_group=None, rd_part=None):
    if parent_group is None:
        groups = Group.objects.all()

    else:
        groups = Group.objects.filter(parent_group=parent_group)

    old_rd_part = None
    rd_part = rd if rd_part is None else rd_part


    for group in groups:

        if find_parent(group).name in rd:
            old_rd_part = rd_part
            rd_part = rd_part.setdefault(group.name, {})

            members = Member.objects.filter(group=group)

            for member in members:
                rd_part[member.name] = member.score

            if len(Group.objects.filter(parent_group=group)) > 0:
                populate_with_groups(group, rd_part)
                rd_part = old_rd_part
            else:
                rd_part = old_rd_part
        else:
            ult_parent = find_parent(group)
            rd_part = rd.setdefault(ult_parent.name, {})
            populate_with_groups(ult_parent, rd_part)

populate_with_groups()

有更简单/正确的方法吗?

0 个答案:

没有答案