Přejít na obsah
Odoo Menu
  • Přihlásit se
  • Vyzkoušejte zdarma
  • Aplikace
    Finance
    • Účetnictví
    • Fakturace
    • Výdaje
    • Spreadsheet (BI)
    • Dokumenty
    • Podpisy
    Prodej
    • CRM
    • Prodej
    • POS Obchod
    • POS Restaurace
    • Předplatné
    • Pronájem
    Webové stránky
    • Webové stránky
    • E-shop
    • Blog
    • Fórum
    • Živý chat
    • eLearning
    Dodavatelský řetězec
    • Sklad
    • Výroba
    • PLM
    • Nákup
    • Údržba
    • Kvalita
    Lidské zdroje
    • Zaměstnanci
    • Nábor
    • Volno
    • Hodnocení zaměstnanců
    • Doporučení
    • Vozový park
    Marketing
    • Marketing sociálních sítí
    • Emailový marketing
    • SMS Marketing
    • Události
    • Marketingová automatizace
    • Dotazníky
    Služby
    • Projekt
    • Časové výkazy
    • Práce v terénu
    • Helpdesk
    • Plánování
    • Schůzky
    Produktivita
    • Diskuze
    • Schvalování
    • IoT
    • VoIP
    • Znalosti
    • WhatsApp
    Aplikace třetích stran Odoo Studio Odoo cloudová platforma
  • Branže
    Maloobchod
    • Knihkupectví
    • Obchod s oblečením
    • Obchod s nábytkem
    • Potraviny
    • Obchod s hardwarem
    • Hračkářství
    Food & Hospitality
    • Bar a Pub
    • Restaurace
    • Fast Food
    • Guest House
    • Distributor nápojů
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architektonická firma
    • Stavba
    • Správa nemovitostí
    • Zahradnictví
    • Asociace vlastníků nemovitosti
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketingová agentura
    • Právník
    • Akvizice talentů
    • Audit a certifikace
    Výroba
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Korporátní dárky
    Zdraví a fitness
    • Sportovní klub
    • Prodejna brýli
    • Fitness Centrum
    • Wellness praktikové
    • Lékárna
    • Kadeřnictví
    Trades
    • Údržbář
    • IT hardware a podpora
    • Solar Energy Systems
    • Výrobce obuvi
    • Úklidové služby
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agentura pro životní prostředí
    • Pronájem billboardů
    • Fotografování
    • Leasing jízdních kol
    • Prodejce softwaru
    Browse all Industries
  • Komunita
    Edukační program
    • Tutoriály
    • Dokumentace
    • Certifikace
    • Vzdělávání
    • Blog
    • Podcast
    Podpora vzdělávání
    • Vzdělávací program
    • Scale Up! Hra na firmu
    • Navštivte Odoo
    Získat software
    • Stáhnout
    • Porovnejte edice
    • Verze
    Spolupráce
    • Github
    • Fórum
    • Události
    • Překlady
    • Stát se partnerem
    • Services for Partners
    • Registrujte svou účetní firmu
    Získat služby
    • Najít partnera
    • Najít účetní
    • Setkejte se s poradcem
    • Implementační služby
    • Zákaznické reference
    • Podpora
    • Upgrady
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Dohodnout demo
  • Ceník
  • Pomoc

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

  • CRM
  • e-Commerce
  • Účetnictví
  • Sklad
  • PoS
  • Projekty
  • MRP
All apps
You need to be registered to interact with the community.
All Posts Lidé Odznaky
Štítky (View all)
odoo accounting v14 pos v15
O tomto fóru
You need to be registered to interact with the community.
All Posts Lidé Odznaky
Štítky (View all)
odoo accounting v14 pos v15
O tomto fóru
Pomoc

Grouped Sums for computed fields

Odebírat

Get notified when there's activity on this post

This question has been flagged
computed-fieldsgroup-byv18CommunityEdition
1 Odpovědět
1657 Zobrazení
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
Zrušit
Avatar
Christoph Farnleitner
Nejlepší odpověď

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
Zrušit
Enjoying the discussion? Don't just read, join in!

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

Přihlásit se
Related Posts Odpovědi Zobrazení Aktivita
Modify Pivot View
Pivot v18 CommunityEdition
Avatar
Avatar
1
čvn 25
1715
Unable to send email notifications through write
notifications v18 CommunityEdition
Avatar
Avatar
1
čvn 25
1760
Upgrading from 17 to 18 : Computed fields
computed-fields Studio v18
Avatar
1
úno 25
2294
Hide Records based on user group only in a particular view
views record_rule v18 CommunityEdition
Avatar
Avatar
Avatar
2
zář 25
1460
Unable to pass context to an action
context server_action v18 CommunityEdition
Avatar
Avatar
1
čvc 25
1594
Komunita
  • Tutoriály
  • Dokumentace
  • Fórum
Open Source
  • Stáhnout
  • Github
  • Runbot
  • Překlady
Služby
  • Odoo.sh hostování
  • Podpora
  • Upgrade
  • Nestandardní vývoj
  • Edukační program
  • Najít účetní
  • Najít partnera
  • Stát se partnerem
O nás
  • Naše společnost
  • Podklady značky
  • Kontakujte nás
  • Práce
  • Události
  • Podcast
  • Blog
  • Zákazníci
  • Právní dokumenty • Soukromí
  • Zabezpečení
الْعَرَبيّة 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 je balíček open-source aplikací, které pokrývají všechny potřeby vaší společnosti: CRM, e-shop, účetnictví, sklady, kasy, projektové řízení a další.

Unikátní nabídka od Odoo poskytuje velmi jednoduché uživatelské rozhraní a vše je integrované na jednom místě.

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