【问题标题】:Dynamic domain for Many2one field based on other model's field基于其他模型字段的 Many2one 字段的动态域
【发布时间】:2019-06-06 20:48:41
【问题描述】:

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

我用的是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 列表中。

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

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

【问题讨论】:

    标签: python odoo odoo-9


    【解决方案1】:

    我在这里使用一种技术来避免 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
    

    【讨论】:

    • 谢谢先生,首先尝试了第二种解决方案,它确实很有效(至少在 odoo 9 中)。
    • 是的,而且比使用onchange事件动态更改域要好。即使在这种情况下,你也不能使用 onchange 可能会覆盖 name_search method,特别是当你准备好有一个树视图并且你不想为你的字段使用子树时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2016-06-10
    • 2019-01-14
    • 1970-01-01
    • 2015-11-09
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多