Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Real Estate
    • Real Estate Agency
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consulting
    • Accounting Firm
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Solar Energy Systems
    • Shoe Maker
    • Serveis de neteja
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Grouped Sums for computed fields

Subscriure's

Get notified when there's activity on this post

This question has been flagged
computed-fieldsgroup-byv18CommunityEdition
1 Respondre
1630 Vistes
Avatar
Shreya Doodipala

I have 2 computed (not stored) monetary fields on my crm.lead model. I want the grouped sums to appear, when I group the leads (based on some other fields on the model).

My XML code has:

<field name="my_deal_share" sum="My Deal Share" widget="monetary" options="{'currency_field': 'company_currency'}" />

<field name="my_profit_share" sum="My Profit Share" widget="monetary" options="{'currency_field': 'company_currency'}" />

I have used the following Python code in my model:

    @api.model

    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):

        _logger.info("Entering read_group method for CrmLead")

        _logger.info(f"Domain: {domain}")

        _logger.info(f"Fields requested: {fields}") # Check if ':sum' is present here

        _logger.info(f"Groupby: {groupby}")


        # Call the original read_group first to get the grouped data

        res = super(CrmLead, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)


        _logger.info(f"Original read_group result (first 2 groups): {res[:2]}")


        # Determine which computed fields need summing

        needs_deal_share_sum = 'my_deal_share:sum' in fields

        needs_profit_share_sum = 'my_profit_share:sum' in fields


        _logger.info(f"Needs Deal Share Sum: {needs_deal_share_sum}")

        _logger.info(f"Needs Profit Share Sum: {needs_profit_share_sum}")


        # Only proceed if at least one of the computed fields' sums is requested

        if needs_deal_share_sum or needs_profit_share_sum:

            for group in res:

                # Get the records for this specific group

                group_domain = domain + (group.get(groupby[0] + '_domain') if groupby else [])

                records_in_group = self.search(group_domain)


                _logger.info(f"Processing group: {group.get(groupby[0])}")

                _logger.info(f"Records in group count: {len(records_in_group)}")


                # Calculate and set the sum for my_deal_share if requested

                if needs_deal_share_sum:

                    computed_my_deal_share_sum = sum(rec.my_deal_share for rec in records_in_group)

                    group['my_deal_share'] = computed_my_deal_share_sum

                    _logger.info(f"Computed my_deal_share_sum: {computed_my_deal_share_sum}")


                # Calculate and set the sum for my_profit_share if requested

                if needs_profit_share_sum:

                    computed_my_profit_share_sum = sum(rec.my_profit_share for rec in records_in_group)

                    group['my_profit_share'] = computed_my_profit_share_sum

                    _logger.info(f"Computed my_profit_share_sum: {computed_my_profit_share_sum}")

            _logger.info(f"Final read_group result (first 2 groups) after custom sums: {res[:2]}")


        return res

When I check logs, I see:

2025-06-20 08:01:42,196 7188 INFO db3 odoo.addons.custom_crm.models.crm_lead: Needs Deal Share Sum: False

2025-06-20 08:01:42,196 7188 INFO db3 odoo.addons.custom_crm.models.crm_lead: Needs Profit Share Sum: False

Thus, these grouped sums are not calculated.

How can I resolve this?


Odoo v18 Community Edition

0
Avatar
Descartar
Avatar
Christoph Farnleitner
Best Answer

Seems like you're looking for something like this, where My Deal Share and My Profit Share are computed, non-stored fields:


Based on the sample data in my database, result (of the core read_group) for a simple group by (grouped by stage_id only) is

[
{
'stage_id': (1, 'New'),
'stage_id_count': 4,
'expected_revenue': 26664.0,
'probability': 0.0,
'__fold': False,
'__domain': ['&', '&', ('type', '=', 'opportunity'), ('user_id', '=', 2), ('stage_id', '=', 1)]
}, {
'stage_id': (2, 'Qualified'),
'stage_id_count': 2,
'expected_revenue': 13332.0,
'probability': 47.725,
'__fold': False,
'__domain': ['&', '&', ('type', '=', 'opportunity'), ('user_id', '=', 2), ('stage_id', '=', 2)]
}, {
'stage_id': (3, 'Proposition'),
'stage_id_count': 1,
'expected_revenue': 4444.0,
'probability': 0.0,
'__fold': False,
'__domain': ['&', '&', ('type', '=', 'opportunity'), ('user_id', '=', 2), ('stage_id', '=', 3)]
}, {
'stage_id': (4, 'Won'),
'stage_id_count': 2,
'expected_revenue': 5555.0,
'probability': 100.0,
'__fold': False,
'__domain': ['&', '&', ('type', '=', 'opportunity'), ('user_id', '=', 2), ('stage_id', '=', 4)]
}
]


Note 1: This is not the group by result of the screenshot, as it would just be to excessive. The principle however is exactly the same.



Therefore, you should need to put your focus on the __domain key of each dictionary in the list only, since each grouping-result provides you with the domain relevant to its records already. Using this domain, you now can simply issue your sum'ming function on the resulting record set.

class CrmLead(models.Model):
_inherit = 'crm.lead'

my_deal_share = fields.Monetary(compute='_compute_my_deal_share')
my_profit_share = fields.Monetary(compute='_compute_my_profit_share')
currency_id = fields.Many2one(related='company_id.currency_id')

def _compute_my_deal_share(self):
for rec in self:
rec.my_deal_share = rec.expected_revenue * 0.5 # or, i.e. a rate based on the currently logged in user, it's team, etc...

def _compute_my_profit_share(self):
for rec in self:
rec.my_profit_share = rec.expected_revenue * 0.1

@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
result = super(CrmLead, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
for group in result:
lead_ids = self.search(group.get('__domain'))
group['my_deal_share'] = sum(lead_ids.mapped('my_deal_share'))
group['my_profit_share'] = sum(lead_ids.mapped('my_profit_share'))
return result


Note 2: Please keep in mind that excessive grouping and or large result sets will affect your database's performance. You may want to consider to the get rid of the search in the loop and try to create a map of all relevant leads that then can be filtered instead.


Note 3: It's easier if you provide an installable example in future...

0
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Modify Pivot View
Pivot v18 CommunityEdition
Avatar
Avatar
1
de juny 25
1699
Unable to send email notifications through write
notifications v18 CommunityEdition
Avatar
Avatar
1
de juny 25
1741
Upgrading from 17 to 18 : Computed fields
computed-fields Studio v18
Avatar
1
de febr. 25
2276
Hide Records based on user group only in a particular view
views record_rule v18 CommunityEdition
Avatar
Avatar
Avatar
2
de set. 25
1440
Unable to pass context to an action
context server_action v18 CommunityEdition
Avatar
Avatar
1
de jul. 25
1569
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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