Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Create a new record in different model

Subscriure's

Get notified when there's activity on this post

This question has been flagged
automatedactionscustomupdaterecord
10 Respostes
16661 Vistes
Avatar
Dominic Anyanna

Hello 

i have the following models . i would like to create a new record in model b once the state of record a switches to unit manager approved . i was able to achieve that with automated actions but dont know how to bring the parts from model a_lines to model b_lines . i would appreciate any pointers 

model a 


class ServiceRequest(models.Model):
_name = 'servicerequest.rider'
_rec_name = 'jobcard_no'
_inherit = ['mail.thread', 'mail.activity.mixin']

    vehicle_id = fields.Many2one('vehicles.rider')
    state = fields.Selection(string="", selection=[('check-in', 'check-in'), ('Technician service completed', 'Technician service completed'), ('Unit Manager parts approved', 'Unit Manager parts approved'), ('store officer parts released', 'store officer parts released'), ('Unit manager quality check', 'Unit manager quality checked'), ('Checked out', 'Checked out'), ], default='check-in', required=False, track_visibility=True, trace_visibility='onchange', )
    jobcard_no = fields.Char(string="Jobcard Number",
default=lambda self: self.env['ir.sequence'].next_by_code('increment_jobcard'),
requires=False, readonly=True, )
    operations = fields.One2many('jobcard.partsline', 'servicerequest_id', 'Parts',
                     copy=True, readonly=True, states={'check-in': [('readonly', False)]})

@api.multi
def write(self, vals):
if vals.get('state'):
if vals.get('state') == 'Confirm':
lines_dict = {
'jobcard_id': self.id,
'operations': [(6, 0, self.operations.parts_id.ids)],
}
self.env['fundrequestw.rider'].create(lines_dict)
return super(ServiceRequest, self).write(vals)




Model a_lines


class JobcardParts(models.Model):
_name = 'jobcard.partsline'

_description = 'Parts Required used'

name = fields.Text(string='Description', required=False)
servicerequest_id = fields.Many2one(comodel_name="servicerequest.rider", index=True, ondelete='cascade')
parts_id = fields.Many2one('product.product', string='Parts',
ondelete='restrict', index=True)
quantity = fields.Integer(string="Quantity", required=False, )


model b 


class FundRequestWorkshop(models.Model):
_name = 'fundrequestw.rider'
_rec_name = 'request_no'
_inherit = ['mail.thread']


_description = 'Fund request workshop'

date = fields.Date(string="Date", default=date.today(), required=False, readonly=True, states={'draft': [('readonly', False)]})
request_no = fields.Char(string="Request Number", default=lambda self: self.env['ir.sequence'].next_by_code('increment_fund_request'), requires=False, readonly=True, trace_visibility='onchange',)
programme_id = fields.Many2one(comodel_name="programme.rider", string="Programme ID", required=False, readonly=True, states={'draft': [('readonly', False)]})
jobcard_id = fields.Many2one(comodel_name="servicerequest.rider", string="Job Card ref", required=False, readonly=True, states={'draft': [('readonly', False)]})
state = fields.Selection(string="", selection=[('draft', 'draft'), ('Requested', 'Requested'), ('Approved', 'Approved'), ('Rejected', 'Rejected'),], required=False, copy=False, default='draft', readonly=True, track_visibility='onchange', )
operations = fields.One2many(
'jobcard.partsline', 'fundrequest_id', 'Parts',
copy=True, readonly=True, states={'draft': [('readonly', False)]},)
part_qty = fields.Float(string="Quantity", required=False, )


Model b_lines


class FundrequestLine(models.Model):
_name = 'fundrequest.partsline'

_description = 'Parts request line'

name = fields.Text(string='Description', required=False)
fundrequest_id = fields.Many2one(comodel_name="fundrequestw.rider", index=True, ondelete='cascade')
parts_id = fields.Many2one('product.product', string='Parts',
ondelete='restrict', index=True)
0
Avatar
Descartar
Avatar
Samo Arko
Best Answer

In model a you'll need to overide the write method and there check the state and then create the record in model b.

@api.multi
def write(self, vals):
if vals.get('state'):
if vals.get('state') == 'Unit Manager parts approved'     # you should really use something shorter 
lines_dict # here get the lines that you want in a dict formatted for creating record in model b lines
self.env['fundrequest.partsline'].create(lines_dict) # here you pass the dict with vals that you want

return super(ServiceRequest, self).write(vals)
1
Avatar
Descartar
Samo Arko

sorry I don't know how to use this new WYSIWYG editor. So that's why the code looks so bad.

Yenthe Van Ginneken (Mainframe Monkey)

Why not use an onchange on the state field and just do a self.env['your.model'].create() though?

Dominic Anyanna
Autor

Thank You for your answer . i have followed your advice but i now have an error (ValueError: Expected singleton: jobcard.partsline(25, 26) )

Samo Arko

That's because you're passing more than one record. You're passing the records with id 25 and 26. You need to pass them one by one. I don't know where this happens but try to do that line with "for rec in self:" (iterate the records one by one in the recordset) and call the method on rec and not on self. Living a like also helps :)

Dominic Anyanna
Autor

Please can you help me with a sample code based on earlier example

Samo Arko

I can't because I don't know on what line it throws this error and what are you doing on that line. You're probably calling a method with the self parameter. so the only help I can offer you is like I wrote in the earlier comment you need to use a for loop to iterate trough the objects.

for rec in self:

rec.the_method_that_throws_error()

But I don't know if that's the problem or something else. Edit your question with the code that throws the error.

Dominic Anyanna
Autor

I have edited the question to include the code

Samo Arko

I think this line is wrong "'operations': [(6, 0, self.operations.parts_id.ids)]," it needs to be 'operations': [(0, 0, {vals_dict1}), (0, 0, {vals_dict2}), ...]. I normally use (6, 0, [ids]) on many2many fields not one2many. But I might be wrong.

Avatar
admin@marutinandanconstruction.in
Best Answer

Did you solve the issue?

0
Avatar
Descartar
Dominic Anyanna
Autor

yes

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

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

Registrar-se
Related Posts Respostes Vistes Activitat
How do I emulate automated actions via writing a custom module?
action module automated actions custom
Avatar
0
d’oct. 23
1859
Code automated actions for custom Sale Order sequences in Odoo 12
automated actions
Avatar
Avatar
1
de febr. 21
5454
Automated Actions : Created Product Name automatically and internal reference automatically
automated actions
Avatar
Avatar
3
de juny 20
5987
Automated actions - creating directories (v13)
automated actions
Avatar
0
de juny 20
3597
How to set automated action to inactive a user on cretin date ?
automated actions
Avatar
0
de febr. 16
4750
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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