基于其他模型的字段的Many2one字段的动态域

时间:2019-06-06 20:48:41

标签: python odoo odoo-9

我在模型中有一个Many2one字段,该字段属于“ One2many”关系,并且我希望该字段仅允许基于相关模型满足某些条件的条目。我该怎么办?

我正在使用 odoo 9 ,而我的问题如下:

我有一个模型,其中包含两个字段:

  1. Many2one:到产品类别。

  2. One2many:表示代表具有相应佣金的产品的模型。

其背后的想法是,合作伙伴可以按类别分组列出允许销售的产品列表。并且在每个类别内,您应该能够构建属于该类别的产品列表,并为每个产品分配自定义佣金值。

我认为我应该使用域来过滤与该类别相对应的产品,但是我无法基于“父”模型的字段来应用过滤器。

这是我的一些代码。请原谅任何变量名不匹配,因为我的代码部分是西班牙语,并且我在旅途中翻译了它。我的解决方案尝试未包括在内,因此您应该可以按照自己的意愿使用帮助代码。

class allowed_products(models.Model):
  _name = 'products.allowed'

  categ_id = fields.Many2one(comodel_name='product.category', string='Product category', required=True)
  products_and_commissions = fields.One2many(comodel_name='product.commission',
    inverse_name='allowed_list_id', string='Products and their commissions')

  partner_id = fields.Many2one(comodel_name='res.partner')

下面是包含具有相应佣金的产品的类(我想根据上述类中的“ categ_id”过滤其“ product_id”字段)

class product_commission(models.Model):
  _name = 'product.commission'

  allowed_list_id = fields.Many2one(comodel_name='products.allowed')

  value = fields.Float('Commission (%)', digits=(16,2), default=30.0, required=True)

#This is the field that should be filtered by corresponding category
  product_id = fields.Many2one('product.product', string='Product', required=True)

例如:

比方说,合作伙伴“ A”可以出售“汽车”(类别)。将类别“汽车”分配到M2o字段后,我只希望能够将“汽车”产品及其相应的佣金添加到“产品委派”的One2many列表中。

我每次得到的都是每个产品的未过滤列表。我读过几个主题,但似乎没有一个对我有用。

任何建议将不胜感激! 谢谢<3

1 个答案:

答案 0 :(得分:0)

我在这里使用一种技术来避免onchange,因为它不会 在编辑模式下被触发:

假设您的产品允许视图如下:

         <field name="categ_id"/>

         <field name="products_and_commissions">
              <tree editable="bottom">
                  <!-- show product that belong to the category if a category is selected
                       else show all product  -->
                   <field name="product_id"  domain="parent.categ_id and [('category_id','child_of', parent.categ_id)] or []" /> 
                  ....
                  ....
                  ....

每当使用更改产品允许的模型中的类别时,您可能也必须使用onchange来清除该字段

   @api.model
   def onchange_categ_id(self):
       self.products_and_commissions = False # you can do better here by keeping some product that belong the new category