How to manually populate Many2Many?

I have the following code (overriding a purchase module):

class Purchase(metaclass=PoolMeta):
    __name__ = 'purchase.purchase'

    items = fields.Many2Many('purchase.purchase-my_module.item', 'purchase', 'item', 
        string = 'Related items', 
        help = 'Items related to this Purchase',

    sales = fields.Many2Many('', 'purchase', 'sale', 
        string = 'Related sale orders', 
        help = 'Sale orders sources',

I want to populate items field with items that I can get from the (I also added items=M2M() in class).
The general idea is to connect items from sales to corresponded purchases.
These items are not saleable/purchaseble items, but just some items that are owned by clients and are the copies of my own class in my_module.


So, I found the way how to do it. Hope the following short example would help others who will search a solution for the same task:

class Purchase(metaclass=PoolMeta):
    __name__ = 'purchase.purchase'

    items = fields.Many2Many('purchase.purchase-my_module.item',...)
    sales = fields.Many2Many('',...)

    # This method is executed when user add/remove from the list of Sale orders in Purchases module 
    @fields.depends('sales') # Many2Many() | the list of sale orders that are origins for the purchase Many2Many
    @fields.depends('items') # Many2Many() | this the list of items I need to fill from sale orders 
    def on_change_sales(self): 
        items_set = {}  # create an empty set, I dont need to keep history 
        for sale in self.sales:  # in sale orders 'items' is also Many2Many() field
            for item in sale.items: # in each sale order I collect all items
                items_set[] = item;  # add each to the set
        self.items = items_set # Eventually I return the set to the purchase.items field.        self.items = items_set # Eventually I return the set to the purchase.items field.

Hope that helps to others.


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.