【问题标题】:Django get all child and subchilds of a parentDjango获取父母的所有孩子和子孩子
【发布时间】:2018-01-29 11:59:25
【问题描述】:

我有一个自我引用的模型,我想在一个查询中获取所有孩子和孩子的孩子等等。 是否有任何查询集来获取与父母相关的所有孩子?

【问题讨论】:

标签: python django django-queryset


【解决方案1】:

我之前在一个项目中做过类似的事情,除了我使用的是 SQLAlachemy。您可以在模型上添加一个属性或类方法,类似于我下面的方法:

除非您将列表理解更改为使用 Django 关系查询(M2M,外键)。

由于您在使用下面的属性时已经拥有该对象,因此您可以在 M2M 关系查询的列表推导中执行类似的操作:

[c.serialize for c in self.related_column.all()]

    @property
    def serialize(self):
        """ Returns a json serializable dict.

        Notes:
            What's cool about this is that the children's key recursively keeps
            calling itself on all of the children of each new node. Causing the
            output to look like which is pretty powerful.

            - Root
                - level_1  
                    - level_2
                        - level_3
                - level_1  
                    - level_2
                        - level_3
                - level_1  
                    - level_2
                        - level_3

        Returns:
            dict: Key value pairs of essential Node data.
        """
        base = {
            'id':                self.id,
            'name':              self.name,
            'min_num':           self.min_num,
            'max_num':           self.max_num,
            'parent_id':         self.parent_id,
            'can_have_children': self.can_have_children

        }
        if self.can_have_children:
            return {**base, 'children': [c.serialize for c in self.sub_nodes]}
        else:
            return base

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2019-05-02
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多