如何创建使用方法 (def) 验证的增量字段(序列)

How to create an incremental field (sequence) that is validated with a method (def)

我有一个疑问:

我创建了一个名为 niu 的字段来增加每个可库存产品类型的值。

niu = fields.Char(string="NIU", compute="_niu_validation", defalut=" ", readonly=True)

使用属性compute=_ niu_validation我调用了同名方法。在此,我想验证产品类型是否为库存类型。

@api.depends('product_id.product_tmpl_id.type')
def _niu_validation(self):
    if 'product_id.product_tmpl_id.type' == 'product':
        niu = lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'sale.order.line')
        return super(SaleOrderLine,self)

另一方面,我在 sale.order.line 模型中为“niu”字段创建了渲染序列。

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">
        <!-- Sequence for sale.order.line -->
        <record id="seq_sale_order_line" model="ir.sequence">
            <field name="name">NIU Sequence</field>
            <field name="code">sale.order.line</field>
            <field name="prefix">00</field>
            <field name="padding">3</field>
        </record>
        </data>
</openerp>

并且在视图中,我希望为每种可库存产品类型,字段 'niu' 增加其值。

图片:http://en.zimagez.com/zimage/viewsequenceniu.php

拜托,我需要帮助,因为我在这方面已经有很长时间了,我无法独自完成。希望得到您的帮助、指点、建议。非常感谢大家。

在您的代码中,您将函数 (lambda) 分配给 niu:

niu = lambda ...

而你returnsuper()return不需要。

要为 niu 字段分配新值,请使用:

niu = value

要增加其值,您可以使用:

sequence = self.env['ir.sequence'].next_by_code('sale.order.line')
for rec in self:
    rec.niu = sequence

使用odoo官方文档(很有用),去这个LINK搜索Computed fields.

编辑: 检查niu是否已经设置(在条件中添加and not rec.niu):

@api.depends('product_id.product_tmpl_id.type')
def _niu_validation(self):
    ir_sequence = self.env['ir.sequence']
    for rec in self:
        if rec.product_id.product_tmpl_id.type == 'product' and not rec.niu:
            rec.niu = ir_sequence.next_by_code('sale.order.line')

感谢 WoLy,你太棒了,你可以解决我的问题。但我还有其他问题。发生的情况是我实际上生成了库存类型产品的序列。但是当我从 header 按下按钮(保存)时,顺序发生了变化。我不明白为什么会这样。
这是我的方法: niu = fields.Char(string="NIU", compute="_niu_validation", default=" ", readonly=True)

@api.depends('product_id.product_tmpl_id.type')
def _niu_validation(self):
    for rec in self:
        if rec.product_id.product_tmpl_id.type == 'product':
                rec.niu = self.env['ir.sequence'].next_by_code('sale.order.line')

请看这张图片。 在按下(保存)按钮之前对产品进行排序。 http://en.zimagez.com/zimage/4s4s4s.php

按下(保存)按钮后对产品进行排序。 http://en.zimagez.com/zimage/8658946.php

如果您看到图像,您会发现序列已更改。我希望顺序保持不变。

我希望你能帮助我,我真的很感激。谢谢。

您可以通过两种方式在odoo中创建自增字段。第一个关于创建记录,另一个关于点击按钮。

# on button click event
@api.one
def submit_application(self):
    if self.application_no == '/':
        sequence_id = self.env['ir.sequence'].search([('code', '=', 'your.sequence.code')])
        sequence_pool = self.env['ir.sequence']
        application_no = sequence_pool.sudo().get_id(sequence_id.id)
        self.write({'application_no': application_no})