Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Create a new record in different model

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
automatedactionscustomupdaterecord
10 Respuestas
16648 Vistas
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
Mejor respuesta

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
Mejor respuesta

Did you solve the issue?

0
Avatar
Descartar
Dominic Anyanna
Autor

yes

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
How do I emulate automated actions via writing a custom module?
action module automated actions custom
Avatar
0
oct 23
1847
Code automated actions for custom Sale Order sequences in Odoo 12
automated actions
Avatar
Avatar
1
feb 21
5442
Automated Actions : Created Product Name automatically and internal reference automatically
automated actions
Avatar
Avatar
3
jun 20
5980
Automated actions - creating directories (v13)
automated actions
Avatar
0
jun 20
3594
How to set automated action to inactive a user on cretin date ?
automated actions
Avatar
0
feb 16
4739
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Sitio web hecho con

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