首页 > 解决方案 > Odoo:在创建时在另一个模型的 many2one 字段中保存当前 ID

问题描述

我正在尝试做的是我正在custom.modify.price为产品创建一个模型,我可以在其中选择特定的标准来选择产品,然后我填写一个影响所有先前选择的价格的百分比. 我希望它为选择中的每个产品,在另一个模型中创建一个新记录,custom.sale.price并且每个记录应该保存在字段中创建它ID的记录。问题是我可以通过覆盖该方法并为其提供值来创建一个新记录,但我无法为其提供当前“尚未创建”的记录custom.modify.pricemany2onecustom.sale.pricecustom.modify.price createIDcustom.modify.price

class CustomModifyPrice(models.Model):
    date = fields.Datetime(string='Date', required=True, default=fields.Datetime.now())
    brand_id = fields.Many2many(comodel_name="custom.brand", string="Brand", required=False, )
    origin_id = fields.Many2many(comodel_name="custom.country", string="Origin", required=False, )
    percentage = fields.Float(string="Percentage")
    product_ids = fields.Many2many(comodel_name="custom.product", string="Products", readonly=True, )
    
    @api.model
    def create(self, vals):
      values = {'product_id': product.id, 'date': vals['date'], 'sell_price': mod_sell_price, 'modification_id': self.id}###self.id returns nothing here
      price = self.env['custom.sale.price'].create(values)
      result = super(CustomModifyPrice, self).create(vals)
      return result

class CustomSalePrice(models.Model):
    product_id = fields.Many2one(comodel_name="custom.product", string="Product", required=False, )
    date = fields.Datetime(string="Date", default=fields.Datetime.now())
    sell_price = fields.Float(string="Selling Price")
    sale_id = fields.Many2one(comodel_name="custom.sale", string="Sales Order", required=False, )


标签: python-3.xodoo-12

解决方案


您需要custom.modify.price使用结果创建和更新值,id然后创建custom.sale.price

@api.model
def create(self, vals):
  result = super(CustomModifyPrice, self).create(vals)
  values = {'modification_id': result.id, ...}
  self.env['custom.sale.price'].create(values)      
  return result

推荐阅读