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

Insert new record

Suscribirse

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

Se marcó esta pregunta
insertsql
4 Respuestas
20228 Vistas
Avatar
Sebastian782

Hello,

I have 2 models A and B.

When i update field_1 on A model i execute a function that should add a new record into B model.

How can i do this?

I read that we can execute SQL request (example belaw) but maybe there is an other way more clean than do an INSERT to add new record?

query = """ SELECT event_id, state, sum(nb_register) 
            FROM event_registration
            WHERE event_id IN %s AND state IN ('draft', 'open', 'done')
            GROUP BY event_id, state """
self._cr.execute(query, (tuple(self.ids),))

Thanks,
Sebastian

1
Avatar
Descartar
Avatar
Akhil P Sivan
Mejor respuesta

You can override the write function of model_A for that, so that when you are saving the record, it create a new record on model_B.

For eg, try the following, if you want to use old api in your v8 module:

from openerp.osv import fields, osv
class class_A(osv.osv):
_name = 'model.A'
_columns = {
'field_A': fields.many2one('res.partner', string="Supplier", required=True),

}

def write(self, cr, uid, ids, vals, context=None):

model_B_obj = self.pool.get('model_B')
model_B_obj.create(cr, uid, ids, {'product_id':ids, 'date':vals['status_date'], 'status':vals['status']}, context)

return super(class_A, self).write(cr, uid, ids, vals, context)

Using new api, you may try like this:

class class_A(models.Model):
_name = 'model.A'

field_A = fields.Many2one('res.partner', string="Supplier", required=True)


 
@api.multi
def write(self, vals):

model_B_obj = self.env['model_B'].create({'product_id':self.id, 'date':self.status_date, 'status':self.status})

return super(class_A, self).write(vals)

1
Avatar
Descartar
Sebastian782
Autor

Hi, thanks. I don't know why, i am not able to make it work. When i change my select field, it seems that it create a record, with the default values of model.B. First, I want to create record in model.B when i save model.A record, so i think the onchange is not good? It seem that it create a record when Second, i want to create the model.B with my values status_date and status of model.A Here below what i wrote: ------------------------------- @api.onchange('status') def on_change_status(self): self.env['order.history'].create({'product_id':self.id, 'date':self.status_date, 'status':self.status}) What i am doing wrong? Thanks.

Akhil P Sivan

Hi Sebastian, I have updated the answer. You don't need to use onchange for that, just need to override the write function of model_A. Try like above.

Sebastian782
Autor

Hi Akhil, thanks for your help. I have this error : TypeError: write() takes at least 2 arguments (2 given)

Sebastian782
Autor

I use the new API

Akhil P Sivan

try without context, as updated above

Sebastian782
Autor

Perfect now Akhil, thanks :)

Avatar
james_p
Mejor respuesta

You can achieve it without firing SQL request. Just add the below method in model A. You can read more here: https://www.odoo.com/documentation/8.0/reference/orm.html Hope that helps.

@api.onchange('field_1')
def create_new_record(self):
self.env['model_b'].create({'field_in_model_b': value})
0
Avatar
Descartar
Avatar
Sebastian782
Autor Mejor respuesta

Hi, thanks.

I don't know why, i am not able to make it work.

When i change my select field, it seems that it create a record, with the default values of model.B.

First, I want to create record in model.B when i save model.A record, so i think the onchange is not good? It seem that it create a record when

Second, i want to create the model.B with my values status_date and status of model.A

Here below what i wrote:

-------------------------------

@api.onchange('status')

def on_change_status(self):

self.env['order.history'].create({'product_id':self.id, 'date':self.status_date, 'status':self.status})

What i am doing wrong?

Thanks.

0
Avatar
Descartar
¿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
Usage Of SQl Queries In odoo
sql
Avatar
Avatar
1
nov 22
7374
sql constraints aren't being detected in my model
sql
Avatar
Avatar
1
oct 21
4255
Odoo on microsoft sql server instead postgres sql?
sql
Avatar
2
nov 18
10976
Odoo 7:Copy property value to new product_template field
sql
Avatar
1
mar 15
4273
Openerp with MS-SQL
sql
Avatar
Avatar
Avatar
Avatar
4
mar 15
6058
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.

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