This question has been flagged
1 Reply
3210 Views

Hi everyone,

I'm working on adding a field to compute the average price of purchasing a product.( sum( price_subtotal ) / sum(qty) )

I inserted the field in the product template form view and it works fine for every single product. on the other hand, in the product template tree view the field shows the same value for all products ( value of sum(price_subtotal_of_all_products)/(sum(qty_of_all_prod) )

my question is, why does the field shows two different values even if it's calculated by one method ?

here is the method:


    def _get_pmp(self, cr, uid, ids, name, arg, context=None):
pol_obj = self.pool.get('purchase.order.line')
res = {}
qty = 0.0
subtot = 0.0
pol_ids = pol_obj.search(cr, uid, [('product_id', 'in', ids)], context=context)
for product in self.browse(cr, uid, ids, context=context):
for line in pol_obj.browse(cr, uid, pol_ids, context):
qty += line.product_qty
subtot += line.price_subtotal
if qty:
res[product.id] = subtot/qty
return res

Avatar
Discard
Best Answer

Hi,

Your issue is when you open form view you have single id in ids but when you open tree view you have list of ids of all opened records on tree view. eg:

suppose you have 80 records in model with corresponding ids [1,2,3,4....80] 
when you click on first form you get ids  = [1]
when you click on second form you get ids = [2]
and so on and it works great for you but when you open a tree view with 80 records
you get value of ids =  [1,2,3,4....80]
and you condition

 pol_ids = pol_obj.search(cr, uid, [('product_id', 'in', ids)], context=context) fails becuase now it is checking in all PO orders not in just one.
try to fix, if more help required leave a message :)

Here you go:

def _get_average_purchase_price(self, cr, uid, ids, name, arg, context=None):
        pol_obj = self.pool.get('purchase.order.line')
        res = {}
        qty = 0.0
        for template in self.browse(cr, uid, ids, context=context):
            #get all purchase order lines with current product template
            res[template.id] = 0.0
            product_id = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id','=',template.id)])
            if len(product_id):
                line_ids = pol_obj.search(cr, uid, [('product_id', '=', product_id[0])], context=context)
                for line in pol_obj.browse(cr, uid, line_ids, context):
                    qty += line.product_qty
                    subtot += line.price_subtotal
                
                    try:
                        res[template.id] = subtot/qty
                    except:
                        pass #there might be case when qty is 0 it would give you error devision by zero
        return res

Avatar
Discard
Author

Thank you Yogesh! i'm going to try it as you said,, i'll let you know of what i get as result