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
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • 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
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • 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

[11.0] Compute dimensional feature for fields, Area by QWEB with units Conversion

Subscriure's

Get notified when there's activity on this post

This question has been flagged
unitsratiocalculationdimensionscomputed-fields
1 Respondre
6465 Vistes
Avatar
Michael Yeung

I am working a Demo through QWEB on my own instance in docker. Trying to make a Area Calculation for products. It is kindly of simple but variable. The goal is to show the Area with unit which the user select. Here is the calculation:

Width * Height /  Ratio of Length ^2 = Area * Ratio of Area

Reference Unit of Length is meter, and reference Unit of Area is M2; The other units are set correctly and tested the ratio.

Float Fields: x_width, x_height, x_area

Many2One Fields: x_size_uom,  x_area_uom
Object Relation: product.uom
Domain: [('category_id.name', '=', 'Length/ Distance')] & [('category_id.name', '=', 'Area')]

This is what I have set for field x_area:

Dependencies: x_width, x_height, x_size_uom, x_area_uom (4 related fields above)
Compute:

for record in self:
 record[('x_area')] = record.x_width * record.x_height / (record.x_size_uom.factor * record.x_size_uom.factor) * record.x_area_uom.factor

 It is working and calculated correctly, no matter what unit of length is calculated but also error popup, listed as below:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 944, in __get__
    value = record.env.cache.get(record, self)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 960, in get
    value = self._data[field][record.id][key]
KeyError: <odoo.api.Environment object at 0x7f295009bb70>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/tools/safe_eval.py", line 348, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 2, in <module>
ZeroDivisionError: float division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 646, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 307, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/usr/lib/python3/dist-packages/odoo/tools/pycompat.py", line 87, in reraise
    raise value
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 683, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 339, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 97, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 332, in checked_call
    result = self.endpoint(*a, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 927, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 512, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 920, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 912, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 689, in call_kw
    return call_kw_multi(method, model, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 680, in call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 4966, in onchange
    record.mapped(dotname)
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 4414, in mapped
    recs = recs._mapped_func(operator.itemgetter(name))
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 4393, in _mapped_func
    vals = [func(rec) for rec in self]
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 4393, in <listcomp>
    vals = [func(rec) for rec in self]
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 4660, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 948, in __get__
    self.determine_value(record)
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 1059, in determine_value
    self.compute_value(recs)
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 1015, in compute_value
    self._compute_value(records)
  File "/usr/lib/python3/dist-packages/odoo/fields.py", line 1008, in _compute_value
    self.compute(records)
  File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_model.py", line 30, in <lambda>
    func = lambda self: safe_eval(text, SAFE_EVAL_BASE, {'self': self}, mode="exec")
  File "/usr/lib/python3/dist-packages/odoo/tools/safe_eval.py", line 371, in safe_eval
    pycompat.reraise(ValueError, ValueError('%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr)), exc_info[2])
  File "/usr/lib/python3/dist-packages/odoo/tools/pycompat.py", line 86, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3/dist-packages/odoo/tools/safe_eval.py", line 348, in safe_eval
    return unsafe_eval(c, globals_dict, locals_dict)
  File "", line 2, in <module>
ValueError: <class 'ZeroDivisionError'>: "float division by zero" while evaluating
"for record in self:\n  record[('x_area')] = record.x_width * record.x_height / (record.x_size_uom.factor * record.x_size_uom.factor) * record.x_area_uom.factor"

I have no ideas how the float divided by zero

This is how I insert into a view:

<label for="x_area" string="Area"/> 
<div>
<field name="x_width" class="oe_inline"/> x <field name="x_height" class="oe_inline"/>
<field name="x_size_uom" class="oe_inline oe_no_button"/> = <br/>
<field name="x_area" class="oe_inline"/><field name="x_area_uom" class="oe_inline oe_no_button"/>
</div>
 
0
Avatar
Descartar
Avatar
Michael Yeung
Autor Best Answer

OK, I have solved the problem above. Here this is my solution below for reference, by QWEB.

First at all, its divided by zero, because I did NOT set a default value for the Many2One field, which means its ZERO definitely. There are three solutions for the situation.

  1. Not to do the divisor. 

  2. Set a default value for the field.

  3. Give a value in the formula temporary

The Area was divided by the factor of x_area_uom, but I found there is another field for multiple (x_size_uom.factor_inv). Therefore, I could just do the calculation as below with the factor_inv.

(record.x_width * record.x_height) * record.x_size_uom.factor_inv * record.x_size_uom1.factor_inv * record.x_area_uom.factor

Since I do NOT know how to set the default for the Many2One field by QWEB. I have decided to go to the third way, give a temp value in the formula. 

(record.x_width * record.x_height) / ((record.x_size_uom.factor * record.x_size_uom1.factor) or 1) * record.x_area_uom.factor

The formula above will convert the Area into the unit of Area (x_area_uom), which is quite successful as what I wanted. On the other hand, I was thinking to round the Area as Rounding Precision of the UOM (x_area_uom.rounding).

Rounding Precision is not only rounding to the precision. It is the value I could charge the customer in the exact quantity as I wanted, by every 0.25, 0.1, 0.2, 1000, etc. According to the Help of Odoo Team writes:

"The computed quantity will be a multiple of this value. Use 1.0 for a Unit of Measure that cannot be further split, such as a piece."

For example, I have 2 units of Area, SQM & SQF. The rounding precision of SQM is 0.1 and SQF is 0.5. When the Area converted from SQM into SQF, its just only multiply by 10.76 (x_area_uom.factor) into SQF, but it doesnt round it to the value of the unit. Therefore I have tried to use ceil() which is a very good function for rounding purpose. The best way to do is to round it by ceiling to the x_area_uom.rounding.

ceil( 'formula above' , x_area_uom.rounding)

However, ceil() is not one of the built-in functions working on the computed-field, round() will drop the value below 5 and I couldn't import math or other function.  (Since it becomes a little complex from now, I will be using the variable for better understanding and displaying.)

    area = (record.x_width * record.x_height) / ((record.x_size_uom.factor * record.x_size_uom1.factor) or 1) * record.x_area_uom.factor
    rp = x_area_uom.rounding

I made the Area (in the unit I want) divided by the value of rounding and round it to an INTEGER plus 1, which is the function of roundup. Then multiply by the value of rounding, which is the function of ceil(). Finally the value of Area became the perfect value that I wanted to charge the customers. Here it is the full formula for your reference by QWEB. (Although there are many times that errors got me, finally....)

for record in self: 
    area = (record.x_width * record.x_height) / ((record.x_size_uom.factor * record.x_size_uom.factor) or 1) * record.x_area_uom.factor
    rp = record.x_size_uom2.rounding
    record['x_area'] = float(int( area / (rp or 1) ) +1) * rp

Please upvote this answer if you like it, or share your solution for the situation above. Thank you!   

int ( area / rp ) makes it an integer after division without precision. Adding 1 just make it ceiling up to the integer of the Rounding Precision. Float the Integer for multiple a float number. Multiply the Rounding Precision makes it back to the Value we calculated in the Unit I wanted.

If you want to know what functions you could use in computed-field. Check out the "Built-in Function of Python" 
https://docs.python.org/3.5/library/functions.html

I really love Odoo, OMG! It could do anything I want, only the matter is how-to.

0
Avatar
Descartar
Michael Yeung
Autor

Sorry, my bad. Its not the same as ceiling, at least it round down when < 0.5

Michael Yeung
Autor

Solved and Edited the answer! Share your idea with me! Thanks!

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
ValueError: forbidden opcode(s) in 'lambda': STORE_ATTR
computed-fields
Avatar
Avatar
1
de juny 25
16894
Make stored compute filed recompute after changing it logic but not depedencies.
computed-fields
Avatar
Avatar
Avatar
Avatar
3
d’abr. 25
7497
Compute Fields Solved
computed-fields
Avatar
Avatar
2
de jul. 24
9297
Odoo computed field
computed-fields
Avatar
Avatar
1
de gen. 24
2766
Compute field odoo 14
computed-fields
Avatar
Avatar
1
de jul. 22
2989
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