Wednesday 9 December 2015

ORM Methods

_search()


Example 1:



def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):

        location_ids = []

        if context is not None and context.get('user_location'):

            ids = [loc.lot_stock_id.id for loc in \

            self.pool.get('res.users').browse(cr, user, user, context=context).od_warehouse_id if loc.lot_stock_id]

            args.append(['id', 'in', ids])

        return super(stock_location, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context)


Example2:



#get sale orders in the selected roster date and order state in progress/manual only

    def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):

        if context is None:

            context={}

        so_ids=[]

        if context.get('roster') and not context.get('roster_date'):

            args.append(['id', 'in', so_ids])

        if context.get('roster') and context.get('roster_date'):

            date = context.get('roster_date')

            qry = """select id from sale_order where state in ('progress','manual') and date_order >= '%s' and date_order < ('%s'::date + '1 day'::interval)"""%(date,date)

            cr.execute(qry)

            res = cr.fetchall()

            if res:

                so_ids.extend([i[0] for i in res])

            args.append(['id', 'in', so_ids])

        return super(sale_order, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context)


write()


    

    Example 1:


    def write(self, cr, uid, ids, vals, context=None):

        line_ids = []

        res = super(sale_order_line, self).write(cr, uid, ids, vals, context=context)

        rec = self.browse(cr, uid, ids, context)[0].order_id

        

        if vals.get('discount') > 10:

            

            self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':True},context)

        else:

            for obj in rec.order_line:

                if obj.discount > 10:

                    line_ids.append(obj.id)

            if len(line_ids) > 0:

                self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':True},context)

            else:

                self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':False},context)

      

        return res


Example2:



def write(self, cr, uid, ids, vals, context=None):

         od_route_shift_obj = self.browse(cr, uid, ids, context=None)

         update_pending_orders = od_route_shift_obj.update_pending_orders

         old_sale_person_id = od_route_shift_obj.sale_person_id.id

         sale_order_pool = self.pool.get('sale.order')

         sale_order_obj = sale_order_pool.browse(cr, uid, ids)

         sale_person_id = sale_order_obj.user_id

         sale_order_ids = sale_order_pool.search(cr, uid, [('od_delivered_user_id', '=', old_sale_person_id),('state', '=', 'draft')])

         if 'sale_person_id' in vals and 'update_pending_orders' in vals:

            if vals['update_pending_orders']:

                new_sale_person_id = vals['sale_person_id']

                if sale_order_ids:

                    sale_order_pool.write(cr, uid, sale_order_ids, {'od_delivered_user_id': new_sale_person_id})

         return super(od_route_shift, self).write(cr, uid, ids, vals, context=context)


  sale_order_pool.write(cr, uid, sale_order_ids, {'od_delivered_user_id': new_sale_person_id})


create()


Example1:


def create(self, cr, uid, vals, context=None):

        res = super(od_hr_expense_loans_description_line, self).create

    (cr, uid, vals, context=context)

        loan_data = self.browse(cr, uid,res)

        product_id = vals['product_id']

        od_hr_expense_loans_description_line_obj = self.pool.get

       ('od.hr.expense.loans.description.line')

        unit_quantity = vals['unit_quantity']

        product_obj = self.pool.get('product.product')

        next_date = vals['date_value']

        unit_amount = vals['unit_amount']

        next_date_strp = datetime.strptime(next_date, '%Y-%m-%d')

        next_date_strp_rel = relativedelta(next_date_strp)

        months = (12*(next_date_strp_rel.years) +(next_date_strp_rel.months+1))

        od_hr_loan_info_line_pool = self.pool.get('od.hr.loan.info.line')

        for i in range(0,unit_quantity):

            next_date_strp = next_date_strp + relativedelta(months=1)

            if product_id:

                salary_pool = self.pool.get('hr.salary.rule')

                salary_rule_ids =  self.pool.get('hr.salary.rule').search

              (cr,uid, [('od_product_id','=',product_id)])

                if salary_rule_ids:

                    salary_rule_data = salary_pool.browse

                 (cr, uid, salary_rule_ids, context=context)[0]

                    od_hr_loan_info_line_pool.create(cr, uid, {

                        'date_value': next_date_strp,

                        'amount': unit_amount,

                        'rule_id': salary_rule_data.id,

                        'hr_expense_loan_id':loan_data.loans_id and loan_data.loans_id.id ,

                })

        return res


Example2:


    def create(self, cr, uid, vals, context=None):

        if vals.get('discount') > 10 and vals.get('order_id'):

            self.pool.get('sale.order').write(cr,uid,[vals.get('order_id')],{'od_sales_man_discount_ctrl':True},context)

        return super(sale_order_line, self).create(cr, uid, vals, context=context)


unlink()


Example1:


@api.multi

def unlink(self):

    for invoice in self:

        if invoice.state not in ('draft', 'cancel'):

            raise Warning(_('You cannot delete an invoice which is not draft or cancelled. You should refund it instead.'))

        elif invoice.internal_number:

            raise Warning(_('You cannot 

delete an invoice after it has been validated (and received a number). You can set it back to "Draft" state and modify its content, then re-confirm it.'))

    return super(account_invoice, self).unlink()


Example2:


@api.multi

def unlink(self):

    for target in self:

        if target.state not in ('draft'):

            raise Warning(_('You cannot delete it,it is not in draft.'))

        return super(od_sales_target, self).unlink()


Example3:


def unlink(self, cr, uid, ids, context=None):

     od_production_planning_obj = self.read(cr, uid, ids, ['manufacturer_line'], context=context)

     unlink_ids = []

     for production in od_production_planning_obj:

        for product in production['manufacturer_line']:

            raise osv.except_osv(_('Invalid Action!'), _('You cannot Delete it,Manufacturing Order Still Existing'))

        unlink_ids.append(production['id'])

    return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)


Example4:


def unlink(self, cr, uid, ids, context=None):

    sale_orders = self.read(cr, uid, ids, ['state'], context=context)

    unlink_ids = []

    for s in sale_orders:

        if s['state'] in ['draft', 'cancel']:

            unlink_ids.append(s['id'])

        else:

            raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it before!'))


        return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)


Example5:



#For lines Exisisting lines unlink at the time of line generation(v7)




def compute_sheet(self, cr, uid, ids, context=None): 
        slip_line_pool = self.pool.get('hr.payslip.line') 
        sequence_obj = self.pool.get('ir.sequence') 
        self._od_generate_ot_details(cr, uid, ids,context=context) 
        for payslip in self.browse(cr, uid, ids, context=context): 
            number = payslip.number or sequence_obj.get(cr, uid, 'salary.slip') 
            #delete old payslip lines 
            old_slipline_ids = slip_line_pool.search(cr, uid, [('slip_id', '=', payslip.id)], context=context) 
#            old_slipline_ids 
            if old_slipline_ids: 
                slip_line_pool.unlink(cr, uid, old_slipline_ids, context=context) 
            if payslip.contract_id: 
                #set the list of contract for which the rules have to be applied 
                contract_ids = [payslip.contract_id.id] 
            else: 
                #if we don't give the contract, then the rules to apply should be for all current contracts of the employee 
                contract_ids = self.get_contract(cr, uid, payslip.employee_id, payslip.date_from, payslip.date_to, context=context) 
            lines = [(0,0,line) for line in self.pool.get('hr.payslip').get_payslip_lines(cr, uid, contract_ids, payslip.id, context=context)] 
            self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context) 
        return True


Example6



    @api.multi 
    def search_product(self): 
        for obj in self: 
            enquiry_line = obj.enquiry_line 
            enquiry_line.unlink() 
        stock_quant_ids = self.env['stock.quant'].search([('product_id', '=', self.product_id.id)]) 
        for quant in stock_quant_ids: 
            if quant.location_id.usage == 'internal': 
                vals = {'enquiry_id':self.id, 
                        'product_id':quant.product_id.id, 
                        #'batch_no':quant.od_batch_no, 
                        'product_uom_qty':quant.qty, 
                        'location_id':quant.location_id.id, 
                        'package_id':quant.package_id.id, 
                        'unit_price':quant.cost, 
                        'in_date':quant.in_date, 
                        'inventory_value':quant.inventory_value, 
                        'lot_id': quant.lot_id and quant.lot_id.id or '' 
                      } 
                self.env['od.product.enquiry.line'].create(vals) 

        return { 
            'name': _('Product Enquiry'), 
            'view_type': 'form', 
            'view_mode': 'form', 
            'res_model': 'od.product.enquiry', 
            'res_id': self.id, 
            'target': 'new', 
            'type': 'ir.actions.act_window', 
        }


search()


Example1:


journal = self.env['account.analytic.journal'].search([('type', '=', journal_type)], limit=1)



Example2:


journal_ids = self.pool.get('account.journal').search(cr, uid,
            [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)],
            limit=1)


browse()


Example1:


prod = product_obj.browse(cr, uid, line[2]['product_id'], context=context)


Example2:


p = self.env['res.partner'].browse(partner_id)



name_get()


Example1:



    def name_get(self, cr, uid, ids, context=None):
        res = []
        for id in ids:
            elmt = self.browse(cr, uid, id, context=context)
            name = "["+str(elmt.code)+"]"+" "+elmt.name
            res.append((id, name))
        return res



No comments:

Post a Comment