Simple Multiplication of two fields in OpenErp - python

I have two fields in a class, in a third field i need the multiplication result of the two fields declared before.
For example:
_columns = {
'Item' : fields.integer('Items'),
'Fecha': fields.date('Fecha del Documento', required=True, select=True),
'Codigo Arancelario' : fields.integer('Codigo Arancelario'),
'Descripcion Arancelaria' : fields.char('Descripcion Arancelaria', size=42, required = True, translate = True),
'Especificaciones Tecnicas' : fields.char('Especificaciones Tecnicas', size=60, required = True, translate = True),
'Cantidad' : fields.float('Cantidad'), 'Unidad de Medida': fields.many2one('product.uom', 'Unidad de Medida'),
'Precio Unitario Declarado' : fields.float('Precio Unitario Declarado'), 'Moneda' : fields.many2one('res.currency', 'Moneda'),
'Valor En Divisas' : Result of the multiplication of 'Precio Unitario Declarado' * 'Cantidad',
'notas' : fields.text('Notas'),
}
Should i use a function field for such a simple calculation?
Is there a simpler way to accomplish this?

function field will be the good option to do such kind of operation. here is the sample code for multiplication of two field using functional field.
def multi_a_b(self, cr, uid, ids, name, arg, context=None):
res = {}
for record in self.browse(cr, uid, ids,context):
res[record.id] = record.field_a * record.field_b
return res
_columns = {
'field_a': fields.integer('A'),
'field_b': fields.integer('B'),
'field_c': fields.function(multi_a_b, type='integer', 'C'),
}

You need to do a combination of these answers.
First define c4 as a functional field as specified in the answer from user1576199, then create the on_change function as defined in the answer from Atul;
def onchange_value(self, cr, uid, ids, c1 = 0.0, c2 = 0.0, c3 = 0.0, context = None):
return {'value': {'c4': c1 + c2 + c3}}
but, put the on_change on the values c1 to c3, not c4, like this...
<field name="c1" on_change="onchange_value(c1, c2, c3, context) />
<field name="c2" on_change="onchange_value(c1, c2, c3, context)/>
<field name="c3" on_change="onchange_value(c1, c2, c3, context)/>
<field name="c4" />
c4 is a functional field but you can still return it in an on_change value clause for other field(s) and the value on the screen will be refreshed but it will not be stored in the database unless you add store = True to the c4 field definition.
If the user changes any of the c1, c2 or c3 fields, the on_change method will be called and the total will be re-calculated and refreshed on the display.

Here is possible solution
from osv import osv, fields
def multi_price_qty(self, cr, uid, ids, name, arg, context=None):
res = {}
for product in self.browse(cr, uid, ids,context):
res[product.id] = product.price * product.qty
return res
class abs_product(osv.Model):
_name = "abs.product"
_columns = {
'code': fields.char('Code', size=32),
'description': fields.char('Description', size=64),
'sizeunit': fields.char('Size /Unit', size=32),
'qty': fields.integer('Quantity', size=32),
'price': fields.integer('Price'),
'pullout': fields.char('Pull-Out', size=32),
'return': fields.char('Return', size=32),
'offtake': fields.char('Offtake', size=32),
'weeksales': fields.char('Weekly Sales', size=32),
'date': fields.date('Date'),
'totalprice': fields.function(multi_price_qty, type='integer', 'Total Price'),
}
abs_product()

I think function field is ok for this type of calculation.
OR another way you can put a button, on button click multiply this two filed values.

Related

Make a field to be obliged and unique , and use it to call recordings,

Please my friends I have a problem that blocks me what is the solution to make a field to be obliged and unique , and this field will servire like to call my reference recordings,
I tried this solution but it is still accepting registrations with the same NumOffre.
class saisir_soumi(osv.osv):
_name='saisir.soumi'
_rec_name = 'NumOffre'
_columns = {
'NumOffre' : fields.char('N° Offre',required=True), # Must be obliged and unique
'organisme_s' : fields.char('Organisme',required=True),
'taxe' : fields.selection([('17','17 %'),('12','12 %'),('10','10 %')],'Taxe Etablissement'),
'des_offre' : fields.char('Designation de l\'offre'),
'mont_marche' : fields.float('Montant Marché'),
'date_depot' : fields.datetime('Date dépot'),
'observation_s' : fields.text('Observation'),
'order_line' : fields.one2many('saisir.soumi.ligne','order_id','soumission_id'),
}
_sql_constraints = [
('uniq_NumOffre', 'unique(NumOffre,id)', "numero offre doit resté unique !"),
]
class saisir_soumi_ligne(osv.osv):
_name ='saisir.soumi.ligne'
def onchange_value(self, cr, uid, ids, prix , quantite, context = None):
return {'value': {'soustotal': prix * quantite}}
def on_change_produit(self, cr, uid, ids, product_id):
val = {}
prod = self.pool.get('product.product').browse(cr, uid, product_id)
if prod:
val['prix'] = prod.list_price
val['qty_stock'] = prod.qty_available
val['garantie'] = prod.warranty
return {'value': val}
_columns= {
'order_id': fields.many2one('saisir.soumission', 'Order Reference'),
'product_id' : fields.many2one('product.product', 'Type Engin'),
'quantite':fields.float(string='Quantité de soumi'),
'qty_stock' : fields.float(string='Quantité Stock'),
'marque' : fields.char('Marque'),
'garantie' : fields.float('Garantie'),
'prix' : fields.float('Prix Unitaire'),
'soustotal' : fields.float('Sous total')
}
class saisir_soumi(osv.osv):
_name ='saisir.soumi'
_columns= {
'order_idd': fields.many2one('saisir.soumission', 'N° Offre'),
'observation_d' : fields.text('Observation'),
'Date_ouv_pli' : fields.date('Date Ouverture Plis'),
'organisme_d' : fields.char('Organisme'),
'nom_prenom_demar' : fields.char('Nom Démarcheur'),
'date_depot_d' : fields.date('Date dépot de soumission'),
}
The constraint unique(NumOffre,id) restrict similar NumOffre and id, I think what you want is unique(NumOffre). also you need to make sure that there are no duplicated field existed before the constraint otherwise it won't work.

How to pass field values of custom model to Qweb report?

I have created a wizard in that i placed a many2one field [names] from another model in which report printing is enabled. What is happening here is when i select one record & clicked on print button it is printing only empty report.so is it possible to fetch the data into report over here.
def print_report(self, cr, uid, ids, context=None):
ob=self.pool.get('book.room')
wizard=self.browse(cr,uid,ids,context=context)
datas = {
'ids': wizard.name,
'model': 'book.room',
'form': ob.browse(cr, uid, wizard.name)#[-1]
# 'form': [{'create_uid': (1, u'Administrator'), 'create_date': '2015-10-20 10:32:42', 'name': (1, u'Nani'), '__last_update': '2015-10-20 10:32:42', 'date_end': '12/10/2015', 'date_start': "13/12/1201", 'write_uid': (1, u'Administrator'), 'write_date': '2015-10-20 10:32:42', 'display_name': u'Nani', 'id': 18}]
}
print datas.get('form')
# print datas,'88888888888888'
# print datas['form'],'9999999999999'
return {
'type': 'ir.actions.report.xml',
'report_name': 'hotel_mng.Booking_Details',
'datas': datas,
}
Thanks in advance
class print_report(osv.TransientModel):
_name='report.wizard'
_columns={
'room1':fields.many2one('hotel.allroom','roomnum','Room No.')
}
def print_report(self, cr, uid, ids, context=None):
current=self.browse(cr,uid,ids)
obj=self.pool.get('book.room')
k=obj.search(cr,uid,[('name','=',current.name.name)],context=context)
context = {}
data = self.read(cr, uid, ids)[0]
datas = {
'ids': k,
'model': 'report.wizard',
'form': data,
'context':context
}
return{
'type' : 'ir.actions.report.xml',
'report_name' : 'hotel_mng.Booking_Details',
'datas' : datas,
}
print_report()
the above code is working fine for me.. it takes names from ref. model and prints report Thanks
def print_report(self, cr, uid, ids, context=None):
datas = {}
a=[]
print "---------------------------------------------------------------"
for phone in self.browse(cr, uid, ids, context=context):
b=phone.selection_item
print b
if context is None:
context = {}
datas['ids'] = context.get('active_ids', [])
datas['model'] = context.get('active_model', 'ir.ui.menu')
datas['value']=b
context.update({'names':b})
return {
'type': 'ir.actions.report.xml',
'report_name': 'sales_invoice.report_mom',
'datas': datas,
'context':context}
at report
<p align="right"><span t-esc="o._context['names']"/></p>

how to retrieve values using onchange in odoo?

I have following two modules. In the following asset1_inspection class I have created two tree views. 'msr_insp': fields.one2many('results.measure','insp_msr','Inspection Measure',),. I will create some measures for each inspection.
After that in feedback.py when I select a particular inspection in 'insp_msr1' I used to get assigned measure for that inspection
config.py
class asset1_inspection(osv.Model):
_name = "asset1.inspection"
_rec_name="inspection_name"
MAINTENANCE_SELECTION=[
('0','Daily'),
('1','Weekly'),
('2','Fortnight'),
('3','Bi-Monthly'),
('4','Quarterly'),
('5','Half-Yearly'),
('6','Yearly'),
('7','Bi-Yearly'),
]
MAINTENANCE_TYPE=[
('0', 'Corrective'),
('1', 'Preventive'),
('2', 'Predictive'),
]
SHOUTDOWN_SELECTION=[
('0','YES'),
('1','NO'),
]
_columns = {
'inspection_name':fields.char('Inspection Type',),
'freq_sel':fields.selection(MAINTENANCE_SELECTION,'Frequency'),
'shut_down':fields.selection(SHOUTDOWN_SELECTION,'Shout Down'),
'main_type':fields.selection(MAINTENANCE_TYPE,'Maintenance Type',),
'insp_id1' : fields.one2many('inspec1.grid','insp_id','BoM',),
'msr_insp' : fields.one2many('results.measure','insp_msr','Inspection Measure',),
}
asset1_inspection()
class inspec1_grid(osv.Model):
_name = 'inspec1.grid'
_columns = {
'insp_name' : fields.char('Part'),
'insp_code' : fields.char('Code'),
'insp_quty' : fields.char('Quantity '),
'insp_uom' : fields.char('UoM'),
'insp_id': fields.many2one('asset1.inspection','Insp Id'),
}
inspec1_grid()
class results_measure(osv.Model):
_name = 'results.measure'
_rec_name='measure'
_columns = {
'measure' : fields.char('Inspection Measure'),
'insp_msr' : fields.many2one('asset1.inspection','Insp Measr'),
}
results_measure()
**feedback.py**
from openerp.osv import fields, osv
from openerp import api
class feedback_form(osv.Model):
_name = 'feedback.form'
_rec_name = 'inspec_type'
_columns={
'location' : fields.char('Substation Location'),
'insp_rslt' : fields.one2many('feedback.tree','insp_rsltts','Inspection Result',),
}
class feedback_tree(osv.Model):
_name = 'feedback.tree'
_columns = {
'insp_type' : fields.many2one('asset1.inspection','Inspection Type',),
'frequency' : fields.char('Frequency'),
'shutdown' : fields.char('Shout Down'),
'insp_msr1' : fields.many2one('results.measure','Result',),
'insp_rsltts': fields.many2one('feedback.form','Result Id'),
}
def get_inspection(self, cr, uid, ids, inspec_type, context=None):
val = {}
if inspec_type:
for det in self.pool.get('asset1.inspection').browse(cr,uid,inspec_type,context=context):
val = {
'insp_msr1' : det.measure,
#'qty' : det.qty,
#'uom' : det.uom,
}
return {'value': val}
To use the on_change you have to go the your view and then to the field that will be changed.
For example:
<field name="my_field" on_change="onchange_method(xx_field_a, xx_field_b)"/>
So in the above example this field will call the method "onchange_method" when it's changed. You can also give it parameters that contain the current values on the form. This is how you retrieve those values.
The onchange_method itself is pretty simple:
def onchange_method(self, cr, uid, ids, xx_field_a, xx_field_b, context=None):
return {'value': {'my_field': xx_field_a * xx_field_b}}
Here you can see I retrieved xx_field_a and xx_field_b from my form because I passed them as parameters in the on_change in the view.

how to add to fields in on field?

In folio_num field I wanted to get two value combined i.e. 'assetmodelid_add' + 'place'. In my case I have done function on change method but their I am getting index not string value. this is complete code i have posted here it has asset.asset and agile.poertfilio1 .py file. please go through it and tell me proper code .i think no need to add .xml file .
from openerp.osv import fields, osv
class asset_asset(osv.osv):
_inherit = "asset.asset"
#_name = "asset_asset"
_rec_name= "folio_num"
_columns = {
'name': fields.char('Asset Name', size=64),
'place': fields.many2one('asset.parentlocation', 'Location'),
'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',select=True, required=True),
'area_id' : fields.many2one('asset.name', 'Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True),
'assetmodelid_add' : fields.many2one('agile.portfolio1','Asset Model Code',domain="[('area_id', '=', area_id)]",),
'folio_num' : fields.char('Folio No',),
'asse_line':fields.one2many('asset.line','emp_id','Name Plate'),
'asse_line2':fields.one2many('asset.part','emp_id1','Parts'),
# 'assed_modelid':fields.many2one('agile.portfolio1','Asset Model ID',select=True, required=True),
'quantity': fields.char('Quantity',size=64),
'uom': fields.char('Uinit of Measure',size=64),
'model_no' : fields.char('Model', size=64),
#'asset_id':fields.many2one('agile.portfolio','Asset ID'),
}
'''def get_asset_parts1(self, cr, uid, ids, assetmodelid_add,model_no, context=None):
val = {}
res = []
if model_no:
val['model_no'] = model_name
return {'value': val}'''
def onchange_first_last(self, cr, uid, ids, place, assetmodelid_add, context=None):
v = {}
asset_val=''
place_val=''
place_obj=self.pool.get('asset.parentlocation')
asset_obj=self.pool.get('agile.portfolio1')
if assetmodelid_add:
asset_val = asset_obj.browse(cr, uid, assetmodelid_add, context=None).name
if place:
place_val = place_obj.browse(cr, uid, place, context=None).name
v['folio_num'] = asset_val + place_val
return {'value': v}
def get_asset_parts(self, cr, uid, ids, assetmodelid_add,context=None):
val = {}
#
res = []
res2 = []
res3 = []
if assetmodelid_add:
for asset in self.pool.get('agile.portfolio1').browse(cr,uid,assetmodelid_add,context=context):
for ass in asset.asspart_id1:
val = {
'pname_id' : ass.asspart_name,
'vsurname' : ass.assvalue_code,
}
res.append(val)
for ass in asset.strat_id1:
val = {
'part_name' : ass.start_name,
'part_code' : ass.strat_code,
'part_quty' : ass.strat_quty,
'part_uom' : ass.strat_uom,
}
res2.append(val)
val['model_no'] = asset.model_name
val.update({'asse_line':res, 'asse_line2':res2,'model_no':asset.model_name })
return {'value': val}
asset_asset()
class asset_attach(osv.osv):
_inherit = "asset.asset"
_columns = {
#'rp_resume1' : fields.Binary(string='Resume'),
#'rp_resume1_name' : fields.Char(string='File name')
#'rp_more1_docs' : fields.many2many('ir.attachment', 'room_partner_attachment_rel', 'room_partner_id', 'attachment_id', 'More Documents'),
'attachments': fields.many2many('ir.attachment', 'partner_id',string="Attachments"),
#'nameee':fields.many2one('ir.attachment','Attachments'),
}
asset_attach()
class asset_model_id(osv.osv):
_inherit = "asset.asset"
_columns = {
'assetcat_id' : fields.char('Asset Catg',)
}
asset_model_id()
class pname_line(osv.osv):
_name='pname.line'
_columns = {
'name':fields.char('Name'),
}
pname_line()
class asset_line(osv.osv):
_name="asset.line"
APPOINTMENT_SELECTION=[
('0','Regular'),
('1','Aditional'),
('2','Deputation'),
]
_columns = {
'pname_id':fields.char('Pname'),
'vsurname':fields.char('Value'),
'emp_id': fields.many2one('asset.asset', 'vendor_id'),
}
asset_line()
class pname_part(osv.osv):
_name='pname.part'
_rec_name = 'namee'
_columns = {
'namee':fields.char('Name'),
}
pname_line()
class asset_part(osv.osv):
_name="asset.part"
#_rec_name = 'part_name'
APPOINTMENT_SELECTION=[
('0','Regular'),
('1','Aditional'),
('2','Deputation'),
]
_columns = {
'part_name':fields.char('Name'),
'part_code':fields.char('Code'),
'part_quty':fields.char('Quantity'),
'part_uom':fields.char('UoM'),
'emp_id1': fields.many2one('asset.asset', 'vendor_id'),
}
asset_part()
class asset_parentlocation(osv.osv):
_name="asset.parentlocation"
_rec_name="parent_location"
_columns = {
'location_name' : fields.char('Asset Location', required=True),
'parent_location' : fields.many2one('asset.parentlocation','Parent Location'),}
def name_get(self, cr, uid, ids, context=None):
if context is None:
context = {}
if not ids:
return []
reads = self.read(cr, uid, ids, ['location_name','parent_location'], context=context)
res = []
for record in reads:
name = record['location_name']
if record['parent_location']:
name = record['parent_location'][1]+' / '+name
res.append((record['id'], name))
return res
agile.portfolio1 .py file here
class asset_catg(osv.Model):
_name="asset.catg"
_rec_name='name1'
_description="Define Asset Catgs"
_columns={ 'name1':fields.char('Asset Catg Names',size=64,required=True),}
asset_catg()
class asset_name(osv.Model):
_name="asset.name"
_rec_name='name'
_description="Define asset name"
_columns={ 'name':fields.char('Asset Name',size=64,required=True),
'material_code' : fields.char('Material Code',),
#'area_type': fields.selection(area_type_lov,'Area Type',required=True),
'asset_catg_id':fields.many2one('asset.catg','Asset Catg Name',size=64,required=True),
}
asset_name()
class asset_config_super(osv.Model):
_name = "asset.config.super"
_description = "Assigning to substation"
_columns = {
'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection', select=True, required=True),
'area_id' : fields.many2one('asset.name', 'Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True),
}
asset_config_super()
#Asset Creation
class agile_portfolio1(osv.Model):
_name = "agile.portfolio1"
_rec_name = 'asset_id_add'
_columns = {
'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',select=True, required=True),
'area_id' : fields.many2one('asset.name','Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]",),
'material_code' : fields.char('Material Code'),
'strat_id1' : fields.one2many('portfolio1.grid','strat_id','BoM',),
'asspart_id1' :fields.one2many('asset1.grid','asspart_id','Specification',),
'asset_id_add' : fields.char('Asset Model Code',),
'make_name' : fields.char('Make',),
'model_name': fields.char('Model',),
#'asset_categ': fields.many2one('asset.cat','Asset Catg',select=True,required=True,ondelete="restrict"),
}
def get_meet_dets(self, cr, uid, ids, area_id, context=None):
val = {}
if area_id:
for det in self.pool.get('asset.name').browse(cr,uid,area_id,context=context):
val = {
'material_code' : det.material_code,
}
return {'value': val}
def onchange_first_last(self, cr, uid, ids, make_name, model_name, context=None):
v = {}
#'area_ref':fields.related('area_ref','area_id',readonly=True,type='char',relation='agile.portfolio1',string='Area'),
if make_name and model_name:
v['asset_id_add'] = make_name + model_name
return {'value': v}
agile_portfolio1()
class portfolio1_grid(osv.Model):
_name = 'portfolio1.grid'
_columns = {
'start_name' : fields.char('Part'),
'strat_code' : fields.char('Code'),
'strat_quty' : fields.char('Quantity '),
'strat_uom' : fields.char('UoM'),
'strat_id': fields.many2one('agile.portfolio1','Strat Id'),
}
portfolio1_grid()
class asset1_grid(osv.Model):
_name = 'asset1.grid'
_columns = {
'asspart_name' : fields.char('Part'),
'assvalue_code' : fields.char('Value'),
'asspart_id': fields.many2one('agile.portfolio1','Specifications'),
}
asset1_grid()
#Inspection Class
class asset1_inspection(osv.Model):
_name = "asset1.inspection"
MAINTENANCE_SELECTION=[
('0','Daily'),
('1','Weekly'),
('2','Fortnight'),
('3','Bi-Monthly'),
('4','Quarterly'),
('5','Half-Yearly'),
('6','Yearly'),
('7','Bi-Yearly'),
]
MAINTENANCE_TYPE=[
('0', 'Corrective'),
('1', 'Preventive'),
('2', 'Predictive'),
]
SHOUTDOWN_SELECTION=[
('0','YES'),
('1','NO'),
]
_columns = {
'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',select=True, required=True),
'area_id' : fields.many2one('asset.name', 'Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True),
'assetmodelid_add' : fields.many2one('agile.portfolio1','Asset Model Code',domain="[('area_id', '=', area_id)]", select=True, required=True),
'inspection_name':fields.char('Inspection Type',),
'freq_sel':fields.selection(MAINTENANCE_SELECTION,'Frequency'),
'shut_down':fields.selection(SHOUTDOWN_SELECTION,'Shout Down'),
'main_type':fields.selection(MAINTENANCE_TYPE,'Maintenance Type',),
'insp_id1' : fields.one2many('inspec1.grid','insp_id','BoM',),
'ainsp_id1' : fields.one2many('assetinspec1.grid','ainsp_id','Asset Maintenance',),
#'asset_type': fields.many2one('asset.cat','Asset Categ'),
#'asset_part_id': fields.many2one('ainspcat_name','Asset Cat',)
}
asset1_inspection()
class inspec1_grid(osv.Model):
_name = 'inspec1.grid'
_columns = {
'insp_name' : fields.char('Part'),
'insp_code' : fields.char('Code'),
'insp_quty' : fields.char('Quantity '),
'insp_uom' : fields.char('UoM'),
'insp_id': fields.many2one('asset1.inspection','Insp Id'),
}
inspec1_grid()
class assetinspec1_grid(osv.Model):
_name = 'assetinspec1.grid'
_columns = {
'ainsp_name' : fields.many2one('assetcat1.grid','Asset Name',),
'ainsp_id': fields.many2one('asset1.inspection','aInsp Id'),
}
assetinspec1_grid()
class asset1_cat(osv.Model):
_name = "asset1.cat"
#_rec_name="asset_catname"
_columns = {
'asset_catname':fields.char('Asset Type',),
'assetcat_id':fields.one2many('assetcat1.grid','ainspcat_id','Asset Name',)
}
asset1_cat()
class assetcat1_grid(osv.Model):
_name = 'assetcat1.grid'
#_rec_name='ainspcat_name'
_columns = {
'ainspcat_name' : fields.char('Asset Names'),
'ainspcat_id': fields.many2one('asset1.cat','AssetCat ID'),
}
assetcat1_grid()
Hear many2one fields always have return the id not the value at that we need to browse the record from the that field to that particular object and use that existing field name as well
you should follow some thing like this.
def onchange_first_last(self, cr, uid, ids, place, assetmodelid_add, context=None):
v = {}
assetmodelid_val=''
place_val=''
place_obj=self.pool.get('asset.parentlocation')
assetmodelid_obj=self.pool.get('agile.portfolio1')
if assetmodelid_add:
assetmodelid_val = assetmodelid_obj.browse(cr, uid, assetmodelid_add, context=None).name
if place:
place_val = place_obj.browse(cr, uid, place, context=None).name
v['folio_num'] = assetmodelid_val + place_val
return {'value': v}
I hope this should helpful for you :)
Try following,
def onchange_first_last(self, cr, uid, ids, place, assetmodelid_add, context=None):
v = {}
asset_val=''
place_val=''
place_obj=self.pool.get('asset.parentlocation')
asset_obj=self.pool.get('agile.portfolio1')
if assetmodelid_add:
asset_val = asset_obj.browse(cr, uid, assetmodelid_add, context=None).asset_id_add
if place:
place_val = place_obj.browse(cr, uid, place, context=None).name
v['folio_num'] = asset_val + place_val
return {'value': v}

How to create record adding one2many values?

Let say I have such classes:
class First(orm.Model):
_name = 'first.class'
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner'),
'res_ids': fields.one2many('second.class', 'first_id', 'Resources'),
}
class Second(orm.Model):
_name = 'second.class'
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner'),
'first_id': fields.many2one('first.class', 'First'),
}
Now I want to write a method, when it is called, it would create First class record taking values from Second class. But I don't understand how I should pass values in one2many field while creating First class.
For example let say I call create like this (this method is inside Second class):
def some_method(cr, uid, ids, context=None):
vals = {}
for obj in self.browse(cr, uid, ids):
#many2one value is easy. I just link one with another like this
vals['partner_id'] = obj.partner_id and obj.partner_id.id or False
#Now the question how to insert values for `res_ids`?
#`res_ids` should take `id` from `second.class`, but how?..
vals['res_ids'] = ??
self.pool.get('first.class').create(cr, uid, vals)
return True
There is a documentation about inserting one2many values here:
https://doc.openerp.com/v6.0/developer/2_5_Objects_Fields_Methods/methods.html/#osv.osv.osv.write
But that is only for write method.
Try this Values, If the second.class obj has partner than one2many is created.
obj = self.browse(cr, uid, ids)[0]
if obj.partner_id:
vals{
'partner_id': obj.partner_id.id,
'res_ids': [(0,0, {
'partner_id': obj.partner_id.id, #give id of partner
'first_id': obj.first_id.id #give id of first
})]
}
self.pool.get('first.class').create(cr, uid, vals)
You can create one record with one2many relation like:
invoice_line_1 = {
'name': 'line description 1',
'price_unit': 100,
'quantity': 1,
}
invoice_line_2 = {
'name': 'line description 2',
'price_unit': 200,
'quantity': 1,
}
invoice = {
'type': 'out_invoice',
'comment': 'Invoice for example',
'state': 'draft',
'partner_id': 1,
'account_id': 19,
'invoice_line': [
(0, 0, invoice_line_1),
(0, 0, invoice_line_2)
]
}
invoice_id = self.pool.get('account.invoice').create(
cr, uid, invoice, context=context)
return invoice_id
You can easily save record in this class
first_class_obj.create(cr,uid,{
'partner_id':partner.id,
res_ids : [
{'partner_id':parner_1.id},
{'partner_id':parner_2.id},
{'partner_id':parner_3.id},.....
]
})
here you can easily pass list of second class object

Categories