Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Food & Hospitality
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Guest House
    • Distribuidor de bebidas
    • Hotel
    Real Estate
    • Real Estate Agency
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consulting
    • Accounting Firm
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Trades
    • Handyman
    • Hardware y asistencia informática
    • Solar Energy Systems
    • Zapatero
    • Servicios de limpieza
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar 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
  • Proyecto
  • 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

SQL vs. ORM ongoing amount

Suscribirse

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

Se marcó esta pregunta
ormsql
1 Responder
5774 Vistas
Avatar
Hermel

Dear community,

I have come up with a ORM method to compute the ongoing sale + credit amount of partners grouped by same register code (aka siren character). However the method is awfully slow and causes performance issues. 

In order to fix the method I have tried translating the ORM method into a SQL query (for greater perfomance). Testing shows that the SQL query performs even worse than the ORM method.

I expect this shouldn't be the case..so... what am I doing wrong ?

class ResPartner(models.Model):
    _inherit = 'res.partner'

    ongoing_amount = fields.Float(
        string='Encours HT',
        help='Le montant total encours hors taxes',
        compute='_get_ongoing_amount',
        store=False,
    )

ORM Method:

    @api.one
    @api.depends('siren')
    def _get_ongoing_amount(self):
        lines_invoice = self.env['account.invoice.line'].search([
            ('invoice_id.state','in',['open']),
            ('partner_id.siren','=',self.siren),
            ('partner_id.siren','!=',False),
            ])

        lines_order = self.env['sale.order.line'].search([
            ('order_partner_id.siren','=',self.siren),
            ('order_partner_id.siren','!=',False),
            ('qty_invoiced','=','0'),
            ('state','in',['sale']),
            ('cash','=',False)
            ])
        self.ongoing_amount = sum(line.price_subtotal for line in lines_invoice) \
        + sum(line.price_subtotal for line in lines_order)

SQL method :

    @api.one
    @api.depends('siren')
    def _get_ongoing_amount(self):
        # make sure param doesn't get to false
        param = self.siren
        if not param:
            param = '999999999'
        sum_lines_invoice = self._cr.execute("""
            SELECT SUM(price_subtotal)
            FROM account_invoice_line
            FULL JOIN account_invoice so ON (state=so.state)
            FULL JOIN res_partner res ON (siren=res.siren)
            WHERE siren = %s
            AND state IN ('open')""", (param,))
        sum_lines_invoice = self._cr.fetchone()[0] or 0.0

        sum_lines_order = self._cr.execute("""
            SELECT SUM(price_subtotal)
            FROM sale_order_line
            WHERE siren = %s
            AND qty_invoiced = '0'
            AND state IN ('sale')
            AND cash IS FALSE""", (param,))
        sum_lines_order = self._cr.fetchone()[0] or 0.0
        
        self.ongoing_amount = sum_lines_invoice + sum_lines_order
0
Avatar
Descartar
Avatar
faOtools
Mejor respuesta

Just a few notes regarding:

  1. Replace your @api.one with @api.multi. Beside @api.one is a deprecated decorator, it is also slower in case of multi records. In particular, if you show the field ongoing_amount in kanban or list view, your method would be launched as many times as many records are shown (usually 80) and all checks would be 80 times more frequent (e.g. the check for non-existing param). If you are sure you require only a single record, put self.ensure_one() at the beginning of your @api.multi method.

  2. When you avoid using ORM, you loose some critical features including security rights. For example, in your case a simple user would see sum by all records by all companies, even though he/she doesn't have right for those. So, just take that in account.

  3. I would also offer to keep 'siren' field right in account.invoice.line as a stored computed field depending on a partner siren (perhaps, also the invoice line state). Although it contradicts sql tables normalizing, it would let you avoid joining the tables which, I guess, is quite resource-consuming. Besides, in my opinion it is better to firstly search by siren and than by state, since the latter records should be represented by a bigger number.

As for the point that SQL is slower than ORM. I can't see here the real reason for that (although 'full join' leads to a few doubts). Perhaps, it is because of a used decorator, or since ORM implied SQL queries are optimized in comparison to your statements. Just as a hint: have a look at _search, search and search_count methods right in the Odoo core. Perhaps, it would lead you to some insights. Besides, if you consider migration to odoo 11 or 12: their cashing is optimized.

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

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

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Usage Of SQl Queries In odoo
sql
Avatar
Avatar
1
nov 22
7398
sql constraints aren't being detected in my model
sql
Avatar
Avatar
1
oct 21
4260
update one model from other model in odoo 12 Resuelto
orm sql clone rowid
Avatar
Avatar
1
dic 19
5368
ORM Relationship in Odoo 12
orm
Avatar
0
sept 19
98
Odoo on microsoft sql server instead postgres sql?
sql
Avatar
2
nov 18
11001
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información 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 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