How to create records before load the form view on new record in odoo? - odoo

I have the following models:
class Order(models.Model):
_name = 'discount_order.order'
partner_id = fields.Many2one('res.partner','Cliente',required=True)
order_lines_ids = fields.One2many('discount_order.order_line', 'order_id', string="Lineas")
obs = fields.Text('Comentarios y observaciones')
class Order_line(models.Model):
_name = 'discount_order.order_line'
order_id = fields.Many2one('discount_order.order', string="Order")
cat_id = fields.Many2one('product.category')
disc_ask = fields.Float('Descuento solicitado')
obs = fields.Char('Comentarios por linea')
I need to create 1 'order_line' for each 'product.category' record, when the user press the new button on the form view. So the new 'order object', already has assigned 'order_lines_ids'

You can set default value of order_lines_ids of discount_order.order model.
Default value you can set from py as well as from xml file.
So when you create new record of model discount_order.order then order_lines_ids automatically set default values.

Related

How to create a record for field using many2one in Odoo 13?

I have 3 models. I used One2many field o put the tree view of model 3 in form view of model 1 and 2.
1/ bao_hiem.py with one2many field:
lstd_baohiem = fields.One2many('lich.su', 'name')
thamchieu = fields.Char('Tham chiếu')
2/ dieu_chinh.py with one2many field:
lstd_dieuchinh = fields.One2many('lich.su', 'name')
thamchieu = fields.Char('Tham chiếu')
And 3/ lich_su.py with many2one field:
name = fields.Many2one('bao.hiem')
name_id = fields.Many2one('bao.hiem')
thamchieu = fields.Char('Tham chiếu')
I want to pass the values (eg: 'name', 'thamchieu') from dieu_chinh.py to lich_su.py and auto record with all those values via a button. So that, in the user's form view of model 1 and 2 can show the recorded value also, called the activity history of 1 user.
The code for the button like this:
def chapthuan(self):
giatri_lstd = self.env['lich.su']
gt = {
'name' : self.name.id,
'thamchieu' : self.thamchieu,
'thoigian' : self.thoigian
}
list_lstd_dieuchinh=[]
for line in self.lstd_dieuchinh :
art = {}
art['name'] = line.name.id
art['lstd_dieuchinh'] = line.lstd_dieuchinh
art['thamchieu'] = line.thamchieu
art['thoigian'] = line.thoigian
list_lstd_dieuchinh.append((0, 0, art))
gt.update({ # add the list of command to gt
'thamchieu': list_lstd_dieuchinh
})
giatri_lstd = giatri_lstd.create(gt)
return True
After click the button 'chapthuan', it can pass the value and create the record with the field 'name', 'date'. But with the field: 'thamchieu' which has relation many2one with model2 is still not worked.
I must select manually in the form view of the user.
So how to create a record with many2one field?
Please help!
Thank you
https://www.odoo.com/documentation/13.0/reference/orm.html#create-update
You are trying to create records by (0, 0, {values}) to name_id by the way of x2many field.
But name_id is Many2one field. That's your programming error.
But the error log you showed happened when you are trying to remove a record that already links to another record. So what I said above is not the main problem... Anyway, I'm a little confused with your code, it looks not so good

How to define a field that automatically takes the mean of all the data of another integer field of the model of which it is foreign key?

I want this field to be predefined, and automatically calculate the average of all integer data in the field of which it is a foreign key.
Exemple :
class Product (models.Model):
title = CharField(...)
#this field set automatically the average, and also update after
#adding new
price_average = FloatField(...)
class ProductItem (models.Model):
title = CharField(...)
price = IntegerField(...)
_product = ForeignKey(Product)
is it possible in this way or do I have to implement a method that does it automatically in the background?
I think that you can overwrite the save method of ProductItem to calculate the average of Product parent, like this.
class Product (models.Model):
title = CharField(...)
#this field set automatically the average, and also update after
#adding new
price_average = FloatField(...)
def calculate_price_average(self):
total = 0
price = 0.0
for item in self.items.all():
total+=1
price+=item.price
self.price_average = price/total if total>0 else 0
self.save()
class ProductItem (models.Model):
title = CharField(...)
price = IntegerField(...)
_product = ForeignKey(Product, related_name='items')
def save(self, *args, **kwargs):
super(ProductItem, self)save(*args, **kwargs):
self._product.calculate_price_average()
So, when you save new product item to Product, the average change the value.

Creating a record on a module when inserting on an other module

I want to create a record on inventory with quantity = 0 whenever I add a new record to products. Is it possible?
I have 2 modules like so :
class productss(models.Model):
_name = 'productss.productss'
name = fields.Char()
description = fields.Text()
price =fields.Float()
class inventory(models.Model):
_name = 'inventory.inventory'
id_product = fields.Many2one(comodel_name='productss.productss')
qte = fields.Integer(compute="_value_qte", store=True)
Yes, it is possible. Just override productss.productss's create() and create an inventory record within:
#api.model
def create(self, values)
record = super().create(values)
# create an inventory
inv_values = {'id_product': record.id, 'qte': 0}
self.env['inventory.inventory'].create(inv_values)
return record
This code requires the "new" Odoo API (V8+) and Python3

I Insert values in stock.picking move_lines but after click on save it Error The Following fields are in valid stock.move in odoo10

This button
<span class="o_stat_value"><field name="test_field"/>Material Out</span>
class SkylineJobOrder(models.Model):
_name = 'skyline.job.order'
_inherit = 'purchase.order'
#api.multi
def action_workorder_out(self):
x = 0
""" This opens the xml view specified in xml_id for the current Work Order in Manufacturing """
self.ensure_one()
xml_id = self.env.context.get('xml_id')
if xml_id:
res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)
production = self.env['mrp.production'].search([('product_id','=',self.product_id.id)])
for item in production:
x = item.bom_id.id
bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])
for record in bomline:
res.update(
context={'default_states':'draft','default_partner_id': self.partner_id.id,'default_move_lines': [(0,0, {'address_in_id':self.partner_id.id,'product_id':record.product_id.id,'product_uom': record.product_uom_id.id,'product_uom_qty':record.product_qty,'scrapped':False,'state':'draft','picking_id':False,'name': 'test','procurement_id': record.operation_id.id,'split_from': self.id,'no_open': True,'no_create':True,'availability':1,'location_dest_id':8,'picking_id':35})]}
)
print res
return res
return False
I inherit purchase.order and create a button and put action of
stock.picking . The working of button is to stockout the values of raw
material of product .so when click on save button is shows that the
following fields are invalid stock.move.
Blockquote
value inserted form bom.line.ids to stock.move through stock.picking using picking_id, location_id,lication_dest_id and 'purchase=ok, in purchase_id.

Custom data in one2many field in Odoo

I am working on this Odoo assignment. I have to make a custom module in which the requirement is like this.
There is a form say "Notebook" it contains a field that comes from 'hr.employee' i.e. Many2one. Next thing this form will contain is a table which 3 columns (Quality, Score, Comment). Now Qualities must be a master table which contains many qualities name.
I have achieved this task in the way SalesOrder form works i.e. for a particular sales order there are multiple sales lines.
But I want all the qualities to be there on form with default score value of 0.
Here is the code
Please tell me the resolution
class qualities_fields(models.Model):
_name = "ayda.qualities.fields"
_description = "Contains only Attributes"
#api.multi
def name_get(self):
data = []
for rows in self:
value = ''
value += rows.quality_name
data.append((rows.id, value))
return data
quality_name = fields.Char(string="Quality Name")
class qualities_data(models.Model):
_name = "qualities.data"
_description = "All points mandatory to be filled"
quality_id = fields.Many2one('notebook', string="Quality IDs")
quality_name = fields.Many2one('qualities.fields', string="Quality Name")
score = fields.Integer(string="Score")
comment = fields.Char(string="Comment")
class notebook(models.Model):
_name = "notebook"
_description = "Checking one2many of qualities"
def createRecords(self):
cr = self.pool.cursor()
quantity_fields = self.pool.get('qualities.fields').search(cr, self.env.uid, [])
quantity_lines = []
for field in quantity_fields:
quality_data = {
'quality_id' : self.id,
'quality_name' : field.id,
'score' : 0,
'comment' : ''
}
quantity_lines.append(quality_data)
return quantity_lines
name = fields.Many2one('hr.employee', string="Name")
qualities_line = fields.One2many('qualities.data', 'quality_id', string="Qualities Line", default=createRecords)
There's an easier way to do this, on the field definition just set the default score to 0
score = fields.Integer(string="Score", default=0)
That way all scores would be zero when they're created