parent 个孩子并在他们之间过滤

parent childs and filtering between them

所以我有 3 个类别。第一个没有 childs,第二个总是有一个 child 但有时没有 parent 有时有 第三类总是没有 parent.

我的目标是从下到上遍历这 3 个类别。

首先我需要检查没有 child 的类别,其次是第二个类别,然后是第三个。

如果满足我的条件我就显示消息,如果不满足我转到另一个类别并检查条件。

所以我写了这段代码,还不错,但也许我可以不用重复自己,让我的代码更简单?

 msg = _("some %s %s message: %s.")
    msgs = []
for line in order.order_line:
    parent_id = line.product_id.categ_id.parent_id
    parent_parent = line.product_id.categ_id.parent_id
    categ_id = line.product_id.categ_id
    categorys = parent_id + parent_parent + categ_id
categorys = parent_id + parent_parent + categ_id
for categ in categorys:
    if not categ.childs_id and categ.qty_for_discount:
        if line.product_qty < categ.qty_for_discount:
            msgs.append(
                msg % (
                    categ.qty_for_discount - line.product_qty,
                    line.product_id.uom_id.name,
                    categ.name
                )
            )
    elif categ.parent_id and categ.child_id and categ.qty_for_discount:
        if line.product_qty < categ.qty_for_discount:
            msgs.append(
                msg % (
                    categ.qty_for_discount - line.product_qty,
                    line.product_id.uom_id.name,
                    categ.name
                )
            )
    else:
        if line.product_qty < categ.qty_for_discount:
            msgs.append(
                msg % (
                    categ.qty_for_discount - line.product_qty,
                    line.product_id.uom_id.name,
                    categ.name
                )
            )

利用 Python 的变量范围。尝试这样的事情:

def your_method(self):
    msgs = []
    def append_msg():
        msgs.append( _("some %s %s message: %s.")% (
            categ.qty_for_discount - line.product_qty,
            line.product_id.uom_id.name,
            categ.name
        ))
    for line in order.order_line:
        parent_id = line.product_id.categ_id.parent_id
        parent_parent = line.product_id.categ_id.parent_id
        categ_id = line.product_id.categ_id
        categories = parent_id + parent_parent + categ_id
        categories = parent_id + parent_parent + categ_id
        for categ in categories:
            if not categ.childs_id and categ.qty_for_discount:
                if line.product_qty < categ.qty_for_discount:
                    append_msg()
            elif categ.parent_id and categ.child_id and categ.qty_for_discount:
                if line.product_qty < categ.qty_for_discount:
                    append_msg()
            else:
                if line.product_qty < categ.qty_for_discount:
                    append_msg()