How to create record adding one2many values? - python

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

Related

Pass list records to many2many field in odoo

I've created a wiz to get the product which are in the field "catagory_select" please look the code below:
class CategorySelect(models.TransientModel):
_name = 'product.group'
category_select = fields.Many2many('product.category', string='Category')
def start_search_product(self):
wiz_form = self.env.ref('product_filter.get_products_form_all', False)
for rec in self.category_select:
product_res = self.env['product.product'].search([('categ_id', '=', rec.ids)])
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', product_res)
return {
'type': 'ir.actions.act_window',
'name': "Product Filtered",
'res_model': 'product.selection',
'target': 'new',
'view_id': wiz_form.id,
'view_mode': 'form',
}
}
here what i done is i have created a method which returns a wizard but i am not getting a way that how shoud i pass the "product_res" to a many2many field in another wizard which is called the return menu.
"Any help will be appreciated"
You can set on context with default fields set with your values.
ctx = self._context.copy()
ctx.update({'default_m2m_fields': [(6, 0, IDS)]}) # on new wizard the m2m fields set with default on context
You can pass the product_res to another wizard using context
1/ Update your start_search_product to pass the product_res ids:
def start_search_product(self):
product_res_ids = [p.id for p in product_res]
context = {'product_ids': product_res_ids}
return {
'type': 'ir.actions.act_window',
'name': "Product Filtered",
'res_model': 'product.selection',
'target': 'new',
'view_id': wiz_form.id,
'view_mode': 'form',
'context': context,
}
}
2/ Get the product ids in function default_get of ProductSelection wizard:
product_ids = fields.Many2many('product.product', 'Products')
#api.model
def default_get(self, default_fields):
res = super(ProductSelection, self).default_get(default_fields)
product_ids = self._context.get('product_ids')
res.update({'product_ids': [(6, 0, product_ids)]})
return res

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.

Print params in report from a wizard

I'm trying to get a report from wizard, I'm pointing to mi res_model:stock.quant from my return:
def print_report(self, cr, uid, ids, context=None):
datas = {'partner' : context.get('cliente'), 'mounth':context.get('mes')}
return {
'type': 'ir.actions.report.xml',
#~ 'report_file': 'stock.uas.wizard',
'report_name': 'stock.report_uas_document',
'report_type': 'qweb-html',
'datas': datas,
'context': context,
'res_model': 'stock.quant',
'src_model': 'stock.quant',
}
I'm fetching the right model and report, but when y try to consume some field I get this error:
QWebException: "'NoneType' object has no attribute 'get_pallets'" while evaluating
And if I try with some function inside the model I get this error:
QWebException: ('MissingError', you'One of the documents you are trying to access has been deleted, please try again after refreshing.')
Like I am in another model with no field and function named la that.but if a do
<span t-esc="o"/>
In the report
y get: stock.quant(42,)
So the question is, how can I get and consume param from a return.
I think I am in the right object, I build this report in traditional way and its word but through a return call function I don't get pass the param.
Your datas is a dictionary and has only two values.
To do as explained above, try this:
def print_report(self, cr, uid, ids, context=None):
assert len(ids) == 1,
datas = {
'ids': ids,
'model': 'stock.quant',
'form': self.read(cr, uid, ids[0], context=context)
}
return {
'type': 'ir.actions.report.xml',
#~ 'report_file': 'stock.uas.wizard',
'report_name': 'stock.report_uas_document',
'report_type': 'qweb-html',
'datas': datas,
'context': context,
'res_model': 'stock.quant',
'src_model': 'stock.quant',
}

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.

Categories