Skip to Content
Odoo Menu
  • Prijavi
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Knjigovodstvo
  • Zaloga
  • PoS
  • Projekt
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Ključne besede (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Ključne besede (View all)
odoo accounting v14 pos v15
About this forum
Pomoč

Can not replicate one2many field of one model to other model.

Naroči se

Get notified when there's activity on this post

This question has been flagged
one2manycreate
2 Odgovori
4859 Prikazi
Avatar
admin@marutinandanconstruction.in

Hi, 

I am developing an app for testing purpose. In this app I need to copy records saved in one model (includes One2many field aswell) to other model by clicking a button that calls the function which is programmed to the stated task. (Same as Quotation ===> Invoice in sales module)

Here is my model

ORIGIN MODEL (Source, Records will be entered via this model)

from odoo import models, fields, api
from datetime import datetime

class cms_project(models.Model):
_name = 'cms.project'
_description = 'Projects'
_order = 'name asc' # asc or desc

name = fields.Char(string="Project ID", required=True, readonly=True, copy=False, index=True, default='New')
project_short = fields.Char(string="Short Name of Project", required=True)
project_desc = fields.Text(string="Full Name of Work", required=True)
client = fields.Many2one('cms.client', 'Client') # Get Client List from cms.client model
project_ecv = fields.Monetary(compute='_compute_ecv', string="Estimated Cost of Project", readonly=True, store=True)
rebate = fields.Float(string="Percentage (+/-)", required=True)
quoted_total = fields.Monetary(string='Quoted Cost Value of the Work', store=True, readonly=True,
compute='_quoted_total')

work_order_number = fields.Char(string="Client Work Order No.")
work_order_date = fields.Date(string='Work Order Date', required=True, index=True, default=datetime.today())
completion_date = fields.Date(string='Estimated Completition Date', required=True, index=True,
default=datetime.today())

completion_time = fields.Integer(compute='_compute_completion_time', string="Completion time (in Days)",
required=True, index=True, store=False)
remaining_completition_days = fields.Integer(compute='_compute_remaining_completition_days',
string="Remaining Completion Time (in Days)")
currency_id = fields.Many2one(related='boq_line.currency_id', depends=['boq_line.currency_id'], store=True,
string='Currency')
boq_line = fields.One2many('cms.boq.lines', 'boq_id', string='BOQ Lines', copy=True, auto_join=True)
note = fields.Text(string="Notes on BOQ")

@api.model
def create(self, vals):
if vals.get('name', 'New') == 'New':
vals['name'] = self.env['ir.sequence'].next_by_code(
'project.id.seq') or 'New'
return super(cms_project, self).create(vals) # Use return command directly without any "RESULT"

_sql_constraints = [
('pr_short_uniq',
'UNIQUE (project_short)',
'Short name already exists.'),
('pr_id_uniq',
'UNIQUE (name)',
'ID already exists.')]

def _compute_completion_time(self):
for record in self:
record.completion_time = (record.completion_date - record.work_order_date).days

def _compute_remaining_completition_days(self):
for record in self:
record.remaining_completition_days = (record.completion_date - fields.Date.today()).days

@api.depends('boq_line.amount')
def _compute_ecv(self):
global order, ecv_total
for order in self:
ecv_total = 0.0
for line in order.boq_line:
ecv_total += line.amount
order.update({'project_ecv': ecv_total})

@api.depends('project_ecv', 'rebate')
def _quoted_total(self):
for order in self:
calculated = order.project_ecv + (order.project_ecv * (order.rebate / 100))
order.update({
'quoted_total': calculated,
})

@api.model
def create_mb(self,cr):

mb_val_list = []
for order in self:
# prepare MB environment
mb_vals = order._prepare_mb()
# prepare MB lines
for line in order.boq_line:
#self.env['mb.entry.line'].create(line._prepare_mb_line())
mb_vals['mb_line'].append((0, 0, line._prepare_mb_line()))
mb_val_list.append(mb_vals)
moves = self.env['mb.entry'].create(mb_val_list)
return moves

@api.model
def _prepare_mb(self):
self.ensure_one()
mb_vals = {
'mb_no': self.name,
'project_short': self.project_short,
'project_desc': self.project_desc,
'project_ecv': self.project_desc,
'client': self.client,
'rebate': self.rebate,
'quoted_total': self.quoted_total,
'work_order_number': self.work_order_number,
'work_order_date': self.work_order_date,
'completion_date': self.completion_date,
'completion_time': self.completion_time,
'remaining_completition_days': self.remaining_completition_days,
'currency_id': self.currency_id,
'mb_line': [],
}
return mb_vals

class cms_boq_lines(models.Model):
_name = 'cms.boq.lines'
_description = "BOQ Lines"
_rec_name = 'item_id'
# name = fields.Char(string="BOQ Lines")
boq_id = fields.Many2one('cms.project', string='BOQ ID', copy=True, required=True, ondelete='cascade', index=True)

item_id = fields.Char(string="SNo.", store=True)
item_short = fields.Many2one('product.product', string='Item', store=True)
item_des = fields.Text(string='Item Description', store=True)
item_qty = fields.Float(string="Estimated QTY.", required=True, digits=(30, 3), store=True)
item_rate = fields.Monetary(string="SOR Rate", required=True, store=True, )
uom = fields.Many2one('uom.uom', string='Per', store=True)
amount = fields.Monetary(compute='_amount', readonly=True, string="Amount", required=True, strore=True)
currency_id = fields.Many2one('res.currency', string='Currency')

@api.depends('item_qty', 'item_rate')
def _amount(self):
for line in self:
qty = line.item_qty
rate = line.item_rate
line.amount = qty * rate

def _prepare_mb_line(self):
self.ensure_one()
res = {
'boq_id': self.boq_id,
'mb_id':self.boq_id,
'item_id': self.item_id,
'item_short': self.item_short,
'item_qty': self.item_qty,
'item_des': self.item_des,
'item_rate': self.item_rate,
'uom': self.uom,
'amount': self.amount,
}
return res    

 

Destination MODEL ( Records will be replicated in this model)


from odoo import models, fields, api
from datetime import datetime

class mb_entry(models.Model):
_name = 'mb.entry'
_description = "Measurement Book"
_rec_name = 'mb_no'
mb_no = fields.Char(string="MB SNo.")

execution_date = fields.Date(string='Execution Date', required=True, index=True, default=datetime.today())
entry_date = fields.Date(string='Entry Date', required=True, index=True, default=datetime.today(), readonly=True)

project = fields.Char(string='Project')
project_short = fields.Char(string="Short Name of Project", required=True)
project_desc = fields.Text(string="Full Name of Work", required=True)

client = fields.Char(string="Client")
project_ecv = fields.Char(string="Estimated Cost of Project", readonly=True, store=True)
rebate = fields.Char(string="Percentage (+/-)", required=True)
quoted_total = fields.Char(string='Quoted Cost Value of the Work', store=True, readonly=True)

work_order_number = fields.Char(string="Client Work Order No.", copy=False)
work_order_date = fields.Date(string='Work Order Date', required=True, index=True)
completion_date = fields.Date(string='Estimated Completition Date', required=True, index=True)

completion_time = fields.Integer(string="Completion time (in Days)",
required=True, index=True, store=False)
remaining_completition_days = fields.Integer(string="Remaining Completion Time (in Days)")
currency_id = fields.Many2one(related='mb_line.currency_id', depends=['mb_line.currency_id'], store=True,
string='Currency')
mb_line = fields.One2many('mb.entry.line', 'mb_id', string='Measurement Book', copy=True, auto_join=True, readonly=True)




@api.onchange('project')
def project_onchange(self):
for rec in self:
if rec.project:
rec.project_short = rec.project.project_short
rec.project_desc = rec.project.project_desc


# def default_get(self):
class mb_entry_line(models.Model):
_name = 'mb.entry.line'
_description = "Measurement Book Lines"
_rec_name = 'mb_id'
mb_id = fields.Many2one('mb.entry',string='MB Lines ID', index=True,
copy=False)

item_id = fields.Char(string="SNo.", store=True, readonly=True)
item_short = fields.Char(string='Item', store=True, readonly=True)
item_qty = fields.Float(string="Estimated QTY.", required=True, digits=(30, 3), store=True, readonly=True)
boq_id = fields.Char(string='BOQ ID')
item_des = fields.Text(string='Item Description', store=True)
item_rate = fields.Monetary(string="SOR Rate", required=True, store=True,)
uom = fields.Char(string='Per', store=True)
amount = fields.Monetary(readonly=True, string="Amount", required=True, strore=True)
currency_id = fields.Many2one('res.currency', string='Currency')

0
Avatar
Opusti
admin@marutinandanconstruction.in
Avtor

FOCUS METHOD

@api.model

def create_mb(self,cr):

mb_val_list = []

for order in self:

# prepare MB environment

mb_vals = order._prepare_mb()

# prepare MB lines

for line in order.boq_line:

#self.env['mb.entry.line'].create(line._prepare_mb_line())

mb_vals['mb_line'].append((0, 0, line._prepare_mb_line()))

mb_val_list.append(mb_vals)

moves = self.env['mb.entry'].create(mb_val_list)

return moves

@api.model

def _prepare_mb(self):

self.ensure_one()

mb_vals = {

'mb_no': self.name,

'project_short': self.project_short,

'project_desc': self.project_desc,

'project_ecv': self.project_desc,

'client': self.client,

'rebate': self.rebate,

'quoted_total': self.quoted_total,

'work_order_number': self.work_order_number,

'work_order_date': self.work_order_date,

'completion_date': self.completion_date,

'completion_time': self.completion_time,

'remaining_completition_days': self.remaining_completition_days,

'currency_id': self.currency_id,

'mb_line': [],

}

return mb_vals

Avatar
admin@marutinandanconstruction.in
Avtor Best Answer

Isuue was with 

@api.model

After romoving, the code worked!!!

0
Avatar
Opusti
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Prijavi
Related Posts Odgovori Prikazi Aktivnost
[8.0] Error saving one2many when edit before save.
one2many create
Avatar
Avatar
1
nov. 17
5125
Best way to create one2many records in backend
one2many create update
Avatar
0
nov. 22
4925
How can I get data from the rows being created in a list view before saving? Solved
one2many create access
Avatar
Avatar
2
sep. 21
17739
one2many update() vs self.env[]
one2many create api
Avatar
0
jul. 21
4518
Failing to write Many2one field Solved
one2many create relationfield
Avatar
Avatar
1
feb. 19
4494
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now