openerp reference

26
Fields Basic Fields boolean() integer() date() datetime() time() char(string,size,translate=False,..) 'name' : fields.char(‘Name',size=256,), text(string, translate=False, ...) 'note' : fields.text('Note'), float(string, digits=(precision,scale), ...) 'score' : fields.float('Score',digits=(2,1)), selection(values, string, ...) 'state': fields.selection([ ('draft','Draft'), ('confirmed','Confirmed') ],'State',required=True,readonly=True), binary(string, filters=None, ...) 'picture': fields.binary(‘Picture', filters='*.png,*.gif'), class TestObject(orm.TransientModel): _name = 'web_tests_demo.model' _columns = { 'name': fields.char("Name", required=True), 'thing': fields.char("Thing"), 'other': fields.char("Other", required=True) } _defaults = { 'other': "bob" } class res_partner_bank(osv.osv): '''Bank Accounts''' _name = "res.partner.bank" _rec_name = "acc_number" _description = __doc__ _order = 'sequence'

Upload: bembolmaniks

Post on 18-Dec-2015

59 views

Category:

Documents


6 download

DESCRIPTION

Openerp Odoo Reference Guide

TRANSCRIPT

  • Fields Basic Fieldsboolean() integer() date() datetime() time() !char(string,size,translate=False,..) 'name' : fields.char(Name',size=256,), !text(string, translate=False, ...) 'note' : fields.text('Note'), !float(string, digits=(precision,scale), ...) 'score' : fields.float('Score',digits=(2,1)), !selection(values, string, ...) 'state': fields.selection([ ('draft','Draft'), ('confirmed','Confirmed') ],'State',required=True,readonly=True), !binary(string, filters=None, ...) 'picture': fields.binary(Picture', filters='*.png,*.gif'),

    class TestObject(orm.TransientModel): _name = 'web_tests_demo.model' ! _columns = { 'name': fields.char("Name", required=True), 'thing': fields.char("Thing"), 'other': fields.char("Other", required=True) } _defaults = { 'other': "bob" } !!class res_partner_bank(osv.osv): '''Bank Accounts''' _name = "res.partner.bank" _rec_name = "acc_number" _description = __doc__ _order = 'sequence'

  • Fields Relational Fieldsmany2one(obj, ondelete='set null', ...) # by convention, many2one fields end with '_id' 'inventor_id': fields.many2one('res.partner','Inventor'), ! # Write values to a many2many field # https://github.com/cormier/openerp-cookbook/blob/master/many2many-write.md !one2many(obj, field_id, ...) # by convention, *2many fields end with '_ids' 'vote_ids': fields.one2many('idea.vote','idea_id','Votes'), !many2many(obj, rel, field1, field2, ...) # obj is the related table, # rel is th name of the go between table # fields are the fields in the go between Table 'sponsor_ids': fields.many2many('res.partner','idea_sponsor_rel', 'idea_id','sponsor_id','Sponsors'), !related(f1, f2, ..., type='float', ...) # Shortcut field equivalent to browsing chained fields f1,f2,...: # chained fields to reach target (f1 required) (51) # type: type of target field ! 'inventor_country_id': fields.related( 'inventor_id','country', type='many2one', relation='res.country', readonly=True, string=Country'), !!! _defaults = { 'date_start': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), 'finance_inst': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).finance_inst, } !!! #Use this to populate Origin #print context and context.get('active_id', False) or False

    Please take a look at your many2many It should be like this !fields.many2many('that object name', 'sql relation table name', 'this object id', 'that object id', 'Field Lable') Eg: in your case the two many2many could be like this !first many2many !'tag_ids': fields.many2many( 'hello', 'notebook_hello_rel', 'notebook_id', 'hello_id', string="Tags" ), Second many2many !'note_ids': fields.many2many( 'notebook', 'notebook_hello_rel', 'hello_id', 'notebook_id', string="Notebooks" ),

  • Fields Relational Fieldsreference(string, selection, size,..) 'contact': fields.reference('Contact',[ ('res.partner','Partner'), ('res.partner.contact','Contact') ]), ! 'doc': fields.reference('Field Label', selection, size), ! # The fields.reference constructor takes 3 main parameters: # where selection contains the list of document models from which values can be selected # (e.g Partners, Products, etc.), in the same form as in a fields.selection declaration. # The key of the selection values must be the model names (e.g. 'res.partner'). !!function(fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, store=False, multi=False,...) ! # Functional field simulating a real field, computed rather than stored # fnct: function to compute the field value (required) def fnct(self, cr, uid, ids, field_name, arg, context): returns a dictionary { idsvalues } with values of type type # fnct_inv: function used to write a value in the field instead def fnct_inv(obj, cr, uid, id, name, value, fnct_inv_arg, context): # type: type of simulated field (can be any other type except 'function') fnct_search: function used to search on this field def fnct_search(obj, cr, uid, obj, name, args): # returns a list of tuples arguments for search(), e.g. [('id','in',[1,3,5])] obj: model _name of simulated field if it is a relational field # store, multi: optimization mechanisms (see usage in Performance Section) !!!

  • Fields Relational Fieldsstore Parameter !It will calculate the field and store the result in the table. The field will be recalculated when certain fields are changed on other objects. It uses the following syntax: !!store = { 'object_name': ( function_name, ['field_name1', 'field_name2'], priority) } !It will call function function_name when any changes are written to fields in the list ['field1','field2'] on object 'object_name'. The function should have the following signature: !def function_name(self, cr, uid, ids, context=None): Where ids will be the ids of records in the other object's table that have changed values in the watched fields. The function should return a list of ids of records in its own table that should have the field recalculated. That list will be sent as a parameter for the main function of the field. !Here's an example from the membership module: !!'membership_state': fields.function( _membership_state, method=True, string='Current membership state', type='selection', selection=STATE, store={ 'account.invoice': (_get_invoice_partner, ['state'], 10), 'membership.membership_line': (_get_partner_id,['state'], 10), 'res.partner': ( lambda self, cr, uid, ids, c={}: ids, ['free_member'], 10) }),

  • Functions Important Module Creation functions#POPUP CONSOLE LOG raise osv.except_osv('Test',context.get('active_ids', False) ) !!!!decode(replace(encode(m.image,'escape')::text,E'\012',''),'base64') as picture !!!! def onchange_discount(self, cr, uid, ids, regular_price, default_discount, addl_discount): res = {} default_discount_price = regular_price - (regular_price * default_discount/100) res['default_discount_amount'] = regular_price * default_discount/100 res['addl_discount_amount'] = default_discount_price * addl_discount/100 res['list_price'] = default_discount_price - (default_discount_price * addl_discount/100) return {'value':res} ! def onchange_city(self, cr, uid, ids, city_id, context=None): if city_id: state_id=self.pool.get('res.country.city').browse(cr, uid, city_id, context).state_id.id zip_code=self.pool.get('res.country.city').browse(cr, uid, city_id, context).zip country_id=self.pool.get('res.country.state').browse(cr, uid, state_id, context).country_id.id return {'value':{'state_id':state_id,'country_id':country_id, 'zip':zip_code}} return {} !!!!! if context is None: context = {} ! po = self.browse(cr, uid, ids[0], context=context) current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context) irmr_obj = self.pool.get('asi.irmr') context.pop('default_state', False)

  • Functions Populate a Many2many records def assign_to_dr(self, cr, uid, ids, context=None): obj_stock_move = self.pool.get('stock.move') obj_delivery_batch = self.pool.get('delivery.batch') if context is None: context = {} ! # Get the values(_columns) from the wizard for wizard in self.browse(cr, uid, ids, context=context): ! rec_ids = context.get('active_ids', False) ! dr = { 'actual_delivery_date' : wizard.actual_delivery_date, 'truck_number' : wizard.truck_number, 'delivery_seq' : wizard.delivery_seq, 'shipping_address' : wizard.shipping_address, 'stock_ids': [(6, 0, rec_ids)], } ! #Create a Delivery Batch based on the vaules in the form dr_id = obj_delivery_batch.create(cr, uid, dr, context=context) !!The stock_ids field is a many-to-many relationship, and the (6, 0, tax_ids) means to replace any existing records with those in stock_move. Because you're calling create(), there's nothing to replace. !A full list of options is in the documentation for the osv class. !For a many2many field, a list of tuples is expected. Here is the list of tuple that are accepted, with the corresponding semantics !(0, 0, { values }) link to a new record that needs to be created with the given values dictionary !(1, ID, { values }) update the linked record with id = ID (write values on it) !(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well) !(3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself) !(4, ID) link to existing record with id = ID (adds a relationship) !(5) unlink all (like using (3,ID) for all linked records) !(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs) !Add aMany2many values 'tax_id': [[6, False, taxes_id]], where taxes_id=[] taxes_id.append()

  • Functions sum function for relational fieldsclass asi_irmr(osv.Model): _name = "asi.irmr" ! def get_result(self, cr, uid, ids, context=None): total = {} for obj in self.browse(cr, uid, ids, context=context): total[obj.id] = sum(o2m.float_field for o2m in obj.o2m_field) return total ! def total_irmr_line(self, cr, uid, ids, field, arg, context=None): total = {} for current_obj in self.browse(cr, uid, ids, context=context): total[current_obj.id] = sum(related_obj.quantity for related_obj in current_obj.irmr_line_ids) return total ! _columns = { 'po_id' : fields.char('POID', size=254), 'irmr_line_ids' : fields.one2many('asi.irmr_line','irmr_id', 'LOT'), 'total_irmr_line' : fields.function(total_irmr_line,type='float', string='Total IRMR'), } !class asi_irmr_line(osv.Model): _name = "asi.irmr_line" _columns = { 'co_number' : fields.char('CO Number', size=254), 'quantity' : fields.float('Quantity', required="True"), }

  • View Important View functions

    # You may define a custom tree view with the fields you want to show and explicitly use it for your many2many field# doc.openerp.com/v6.0/developer/2_6_views_events/views/specify_view_to_use.html ! # where 'tree_view_ref' points to your custom tree view !#display a different namein the selection ! !!!#Compute for Gross Proceeds = installment_amt x 1000 / rate (Proceeds Rate) cr.execute("SELECT rate FROM lending_rate_proceed WHERE rate_id=%s AND term=%s",(rate_id,terms)) result = cr.fetchone() if result: gross_proceeds = installment_amt*1000/result[0] else: gross_proceeds = 0

    Specify a view to use

  • ModuleAdd a function/action to the

    More drop down

    ! account.invoice.confirm.form account.invoice.confirm Once draft invoices are confirmed, you will not be able to modify them. The invoices will receive a unique number and journal items will be created in your chart of accounts. or !

  • ModuleCreate a new module

    from osv import osv, fields !class idea(osv.Model): _name = 'idea.idea' _columns = { 'name': fields.char('Title', size=64, required=True, translate=True), } _defaults = { 'active': True, # ideas 'state': 'draft', # ideas } ! def _check_name(self,cr,uid,ids): for idea in self.browse(cr, uid, ids): if 'spam' in idea.name: return False # Can't create ideas with spam! return True _sql_constraints = [('name_uniq','unique(name)', 'Ideas must be unique!')] _constraints = [(_check_name, 'Please avoid spam in ideas !', ['name'])]

    ! model.name.action model.name tree,form ! model.name.tree model.name !! model.name.form model.name ! model.name.search model.name ! ! !

    Create Secondary View: ! asi.irmr_line.tree2 asi.irmr_line

  • ModuleModify Existing Forms

    model.name.form model.name red:product_qty==0 # Note: Don't forget to do xml escaping when appropriate (> == > < == ('field_name', 'operator', value) !field_name : a valid name of field of the object model or in the database table !operator : valid operators are =, !=, >, >=,

  • SUPER Domain Filtering def write(self, cr, uid, ids, vals, context=None): student = self.pool.get('lsgh.student') # if student_id has been changed, update alias_model_id accordingly if vals.get('student_id'): print vals.get('student_id') student_with_this_partner = student.search(cr, uid, [('partner_id','=',vals.get('id'))], context=context) student.write(cr, uid, student_with_this_partner, {'partner_id': False}) student.write(cr, uid, student_id, {'partner_id': vals.get('id')}) ! else: student_with_this_partner = student.search(cr, uid, [('partner_id','=',vals.get('id'))], context=context) student.write(cr, uid, student_with_this_partner, {'partner_id': False}) ! return super(lsgh_res_partner, self).write(cr, uid, ids, vals, context=context) ! def create(self, cr, uid, vals, context=None): if vals.get('student_id'): print vals.get('student_id') return super(lsgh_res_partner, self).create( cr, uid, vals, context=None)

  • WARNING Domain Filteringraise osv.except_osv('Test',context.get('active_ids', False) ) !! def on_change_method(self, cr, uid, ids, field_name, field_value2,..., context): #The result will be stored in a dictionary res = {} #Now you can change other fields with the updated values passed as parameters res['field_name_3'] = field_value2 warning = { 'title': _("Warning"), 'message': _('Warning message'), } return {'value': res.get('value',{}), 'warning':warning} !!

  • Modify forminherit x.tree x !! x.form x ! x.search x

    from openerp.osv import fields,osv from openerp import tools !!class prostar_account_move(osv.Model): _inherit = "account.move" _columns = { 'jv_num': fields.char('JV Number'), }