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

Odoo 15 - compute method triggered twice every time?

Suscribirse

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

Se marcó esta pregunta
computecomputedcomputed-fieldsv15
2 Respuestas
7842 Vistas
Avatar
Fred Nunes

Hi all,


I have noticed a behavior on some of my computed fields that I can't understand. I have the following field (toy example):

field_x = fields.Boolean(string="Field X", compute="_compute_field_x", store=True)


Then function  _compute_field_x is as follows:


@api.depends("field_y", "field_z") # none of these are computed def  _compute_field_x(self):
    for record in self:
        print('hi')
        if record.field_y = 'Something':
            record.field_x = "A"
        elif record.field_z = 'Something Else':
            record.field_x = "B"
        else:
            record.field_x = "C"
    

For some reason, whenever I change either field_y or field_z on the model's form view, the message "hi" is printed twice: once before the write() method is called (to update field_y or field_z), and then once again after the write method is concluded. And even stranger, is that when the method is called AFTER the write method, it record.field_y or record.field_z still show the values pre-write.

In my case, this is a problem, because I wanted to send an email warning when field_x changes, but if I do it on the compute method it will end up sending the email twice.

If someone could clarify this behavior for me, I'd really appreciate it!

1
Avatar
Descartar
Avatar
Fred Nunes
Autor Mejor respuesta

In case this might help someone in the future - I was able to "fix" the problem of sending the email twice by checking if we are working in the local cache. I noticed the first time the compute function ran, the record being modified had an ID of type "odoo.models.NewId", which I assume is a temporary object Odoo uses  while the form is open, before actually writing to the database. So I simply check this and prevent the email functionality from running:

if not isinstance(record.id, models.NewId):

    send_email(...)

else:

    pass


3
Avatar
Descartar
Avatar
Waleed Ali Mohsen
Mejor respuesta

Hi, Regardless of the code you posted as the code has some syntax errors and will not work and I think you provided it as example.

The computed method  (if store = True) is called once one of the dependencies fields changes so it will be called once you change the value in the form and it will be invoked on a pseudo-record that contains the values present in the form and not yet saved to the DB (  pseudo-record ) so you will get the first message and once you save the record the write method called and the value of field_y or fieldz changes in DB so the computed  will be called again. 

BTW, if computed field is not stored the computed method will be called every time when the field is accessed.

To send your email I prefer to override write method and send your email whenever the field_x changes.


0
Avatar
Descartar
Fred Nunes
Autor

Hi Waleed, thanks for your comment, it clarified the situation.
Overwriting the "write" method was my initial approach, as I am already doing it with other fields. However, it seems that the write method is not invoked when a computed field is changed.
To explain better: when I changed field_y (to "Something", for example), field_x is recomputed, but the write method is only called once with values = {"field_y": "Something"}. The field_x does not show up. I am not sure how Odoo is writing field_x to the database in the backend, but it does not go through Model.write!

Waleed Ali Mohsen

The computed method called every time if there is changes in the field and depend on your condition the field_x will be recomputed but the field_x will not shown in write method values. I'm not diving deep on how the computed field calculated and updated in DB but I think they update field_x using SQL Command. Will try to search and let you know

Fred Nunes
Autor

Thanks Waleed :) if the write method was called with the updated values, it would indeed fix my problem. For now I haven't found a solution but it's not critical.
Thanks for your effort!

Waleed Ali Mohsen

The computed field is not shown in write method and it's save in cache and then set to the DB from cache. So you don't the calculated field you can check your condition directly from overrided write and create method.

Fred Nunes
Autor

Sorry, I don't understand what you mean by "So you don't the calculated field you can check your condition directly from overrided write and create method."!
But thanks for clarifying the cache thing, makes sense!

Waleed Ali Mohsen

Sorry I mean if the field_x is only flag to send email, you don't want it just put the same condition you did in computed field in write method and send the email.

Fred Nunes
Autor

That was a good suggestion, unfortunately field_x is not a flag but rather a value. I want to send an email updating of the new value. I can probably hack some way to infer if the value changed or not during the write method :) I'll have to see if the additional complexity is worth it.
Thanks a lot!

¿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
Compute field to store in DB
computed-fields v15
Avatar
Avatar
1
jun 23
3859
computed field doesnt work with a domain
fleet computed-fields v15
Avatar
0
abr 24
2244
Why this computed field doest not work? Please Need Help
computed computed-fields solution
Avatar
Avatar
1
may 23
3047
Compute if time is Between 00:00 and 07:00. Resuelto
datetime compute v15
Avatar
1
ene 23
2795
odoo 15 compute days differance Resuelto
attributeerror computed-fields v15
Avatar
Avatar
Avatar
2
sept 22
3259
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