Passa al contenuto
Odoo Menu
  • Accedi
  • Provalo gratis
  • App
    Finanze
    • Contabilità
    • Fatturazione
    • Note spese
    • Fogli di calcolo (BI)
    • Documenti
    • Firma
    Vendite
    • CRM
    • Vendite
    • Punto vendita Negozio
    • Punto vendita Ristorante
    • Abbonamenti
    • Noleggi
    Siti web
    • Configuratore sito web
    • E-commerce
    • Blog
    • Forum
    • Live chat
    • E-learning
    Supply chain
    • Magazzino
    • Produzione
    • PLM
    • Acquisti
    • Manutenzione
    • Qualità
    Risorse umane
    • Dipendenti
    • Assunzioni
    • Ferie
    • Valutazioni
    • Referral dipendenti
    • Parco veicoli
    Marketing
    • Social marketing
    • E-mail marketing
    • SMS marketing
    • Eventi
    • Marketing automation
    • Sondaggi
    Servizi
    • Progetti
    • Fogli ore
    • Assistenza sul campo
    • Helpdesk
    • Pianificazione
    • Appuntamenti
    Produttività
    • Comunicazioni
    • Approvazioni
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    App di terze parti Odoo Studio Piattaforma cloud Odoo
  • Settori
    Retail
    • Libreria
    • Negozio di abbigliamento
    • Negozio di arredamento
    • Alimentari
    • Ferramenta
    • Negozio di giocattoli
    Cibo e ospitalità
    • Bar e pub
    • Ristorante
    • Fast food
    • Pensione
    • Grossista di bevande
    • Hotel
    Agenzia immobiliare
    • Agenzia immobiliare
    • Studio di architettura
    • Edilizia
    • Gestione immobiliare
    • Impresa di giardinaggio
    • Associazione di proprietari immobiliari
    Consulenza
    • Società di contabilità
    • Partner Odoo
    • Agenzia di marketing
    • Studio legale
    • Selezione del personale
    • Audit e certificazione
    Produzione
    • Tessile
    • Metallo
    • Arredamenti
    • Alimentare
    • Birrificio
    • Ditta di regalistica aziendale
    Benessere e sport
    • Club sportivo
    • Negozio di ottica
    • Centro fitness
    • Centro benessere
    • Farmacia
    • Parrucchiere
    Commercio
    • Tuttofare
    • Hardware e assistenza IT
    • Ditta di installazione di pannelli solari
    • Calzolaio
    • Servizi di pulizia
    • Servizi di climatizzazione
    Altro
    • Organizzazione non profit
    • Ente per la tutela ambientale
    • Agenzia di cartellonistica pubblicitaria
    • Studio fotografico
    • Punto noleggio di biciclette
    • Rivenditore di software
    Carica tutti i settori
  • Community
    Apprendimento
    • Tutorial
    • Documentazione
    • Certificazioni 
    • Formazione
    • Blog
    • Podcast
    Potenzia la tua formazione
    • Programma educativo
    • Scale Up! Business Game
    • Visita Odoo
    Ottieni il software
    • Scarica
    • Versioni a confronto
    • Note di versione
    Collabora
    • Github
    • Forum
    • Eventi
    • Traduzioni
    • Diventa nostro partner
    • Servizi per partner
    • Registra la tua società di contabilità
    Ottieni servizi
    • Trova un partner
    • Trova un contabile
    • Incontra un esperto
    • Servizi di implementazione
    • Testimonianze dei clienti
    • Supporto
    • Aggiornamenti
    GitHub Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Richiedi una demo
  • Prezzi
  • Aiuto

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

  • CRM
  • e-Commerce
  • Contabilità
  • Magazzino
  • PoS
  • Progetti
  • MRP
All apps
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
Assistenza

SQL vs. ORM ongoing amount

Iscriviti

Ricevi una notifica quando c'è un'attività per questo post

La domanda è stata contrassegnata
ormsql
1 Rispondi
5786 Visualizzazioni
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
Abbandona
Avatar
faOtools
Risposta migliore

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
Abbandona
Ti stai godendo la conversazione? Non leggere soltanto, partecipa anche tu!

Crea un account oggi per scoprire funzionalità esclusive ed entrare a far parte della nostra fantastica community!

Registrati
Post correlati Risposte Visualizzazioni Attività
Usage Of SQl Queries In odoo
sql
Avatar
Avatar
1
nov 22
7424
sql constraints aren't being detected in my model
sql
Avatar
Avatar
1
ott 21
4289
update one model from other model in odoo 12 Risolto
orm sql clone rowid
Avatar
Avatar
1
dic 19
5374
ORM Relationship in Odoo 12
orm
Avatar
0
set 19
98
Odoo on microsoft sql server instead postgres sql?
sql
Avatar
2
nov 18
11009
Community
  • Tutorial
  • Documentazione
  • Forum
Open source
  • Scarica
  • Github
  • Runbot
  • Traduzioni
Servizi
  • Hosting Odoo.sh
  • Supporto
  • Aggiornamenti
  • Sviluppi personalizzati
  • Formazione
  • Trova un contabile
  • Trova un partner
  • Diventa nostro partner
Chi siamo
  • La nostra azienda
  • Branding
  • Contattaci
  • Lavora con noi
  • Eventi
  • Podcast
  • Blog
  • Clienti
  • Note legali • Privacy
  • Sicurezza
الْعَرَبيّة 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 è un gestionale di applicazioni aziendali open source pensato per coprire tutte le esigenze della tua azienda: CRM, Vendite, E-commerce, Magazzino, Produzione, Fatturazione elettronica, Project Management e molto altro.

Il punto di forza di Odoo è quello di offrire un ecosistema unico di app facili da usare, intuitive e completamente integrate tra loro.

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