使用while循环直到没有记录,而不是fo循环

2024-05-19 08:11:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在stock.move表中有记录,它与stock.move.reconcileOne2many关系,列move_to_idstock.move表中另一个记录的ID。所以这条链可以是成千上万条记录。你知道吗

正如您在我的示例中所看到的,我循环遍历所有记录并逐层向下,但正如我之前所说的,可能有数千个链接的记录,因此我的方法在这里不起作用。你知道吗

我知道我可能需要在这里使用while循环,类似于while there is move_to_ids,然后我应该循环记录并不断向列表中添加id,但我就是不知道怎么做。你知道吗

  • move1(stock.move ID = 10)与内部2个记录有One2many关系的记录:move_to_idsstock.move.reconcile

  • 每个move_to_ids都有move_to_id(many2one, 'stock.move' ID = 11)

  • 每个move_to_id(stock.move, ID=11)记录都有任意数量的move_to_ids (库存.移动.对账) and each of this移动到\u idrecords have移动到\u id('库存.移动',ID=12)`依此类推。

所以基本上我想添加to list all move_to_idid 10、11、12等,以列出所有相关的move_to_ids。你知道吗

moves_to_recalculate = [10,11,12]依此类推,直到有0move_to_ids可从中获取move_to_id。你知道吗

class StockMove(models.Model):
_name = 'stock.move'

move_to_ids = fields.One2many(
    'stock.move.reconcile', 'move_from_id', string='Move to')

 move_from_ids = fields.One2many(
    'stock.move.reconcile', 'move_to_id', string='Move From'
)
class StockMoveReconcile(models.Model):
    _name = 'stock.move.reconcile'
    _description = 'Stock Move Reconcile'

    move_to_id = fields.Many2one('stock.move', string='Move To')
    move_from_id = fields.Many2one('stock.move', string='Move From')

def recalculate(self):
    moves = self.browse(('active_ids'))
    moves_to_recalculate = []
    for move1 in moves:
        #I add my first move in chain to list
        moves_to_recalculate.append(move1.id)
        #First move have 2 moves_to_ids so i make another loop to add it ID to list
        for second_tier_move in move.move_to_ids:
            moves_to_recalculate.appen(second_tier_move.move_to_id.id)
            # secont tier move has 1 move_to_ids so i do another loop, and add it's ID to list.
            for third_tier_move in second_tier_move.move_to_ids:
                moves_to_recalculate.appen(third_tier_move.move_to_id.id)
                #third_tier_move has another move_to_ids , and so on.

Tags: toididsfieldsmovestock记录list
1条回答
网友
1楼 · 发布于 2024-05-19 08:11:27

如果我理解正确的话,这里要解决的问题基本上是在树结构中进行搜索,在树结构中您试图获取父节点的所有子节点。你可以用一种递归的方式来做,我认为这样做是可行的。你知道吗

def get_moves_to_ids(move):
    if not move.move_to_ids:
       return [move.id]
    move_to_ids = []
    for move in move.move_to_ids:
       move_to_ids.extend(get_moves_to_ids(move))
    return move_to_ids

def recalculate(self):
    moves = self.browse(('active_ids'))
    moves_to_recalculate = []
    for move in moves:
        moves_to_recalculate.extend(get_moves_to_ids(move))
    ...

抱歉,我无法测试代码,所以可能有一些错误。如果那样的话,请告诉我,我会尽快更新答案。但是,至少我希望它能给你一个解决问题的方法。你知道吗

相关问题 更多 >

    热门问题