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

How to Automatically Assign SKU (internal reference code) to Products depending on attributes?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
automatedvariantskuv14AutomatedActions
1 Respondre
7062 Vistes
Avatar
James Camfield

I want to automatically assign a SKU (internal reference code) to products depending on if they have the attribute "Organic". If Variants are created I want them only to be given an SKU if they have the attribute "Organic.



My current automated Action:

Model: Product

Active: True

Trigger: On Creation & Update

Trigger Fields:

Before Update Domain: Match all records

Apply on:     Product Attributes > Values > Value = "Organic

                     Internal Reference is not set

                     Product Category > Name = "Food"

Action To Do : Update the Record

Data to write:

                      Field: Internal Reference (product.product)

                      Evaluation Type : Python expression

                      Value: env['ir.sequence'].next_by_code('organic_sku')



When I create a product and give it many variants, all of the variants are given SKUs even though only one of the variants had organic. 

(example the variants: (product1, organic, blue), (product2, conventional, red) and (product3, conventional, green) will all be given an SKU even though only product1 is organic). 


How can it give each variant an SKU only if that variant is Organic?


Thanks for the Help

James Camfield

Odoo 14.0+e (Enterprise Edition)

0
Avatar
Descartar
Avatar
Sudhir Arya (ERP Harbor Consulting Services)
Best Answer

I think you need to write a python code in the server action.

Create a server action with Action "To Do='Execute Python Code'" and add the following code:

for prod in records:
for tmp_attr_val in prod.product_template_attribute_value_ids:
if tmp_attr_val.attribute_id.name == 'Organic':
prod.default_code = env['ir.sequence'].next_by_code('organic_sku')





4
Avatar
Descartar
James Camfield
Autor

Thanks for responding!

I tried using your code, but it wouldn't let me save and had this error message:

forbidden opcode(s) in "# Available variables:\n# - env: Odoo Environment on which the action is triggered\n# - model: Odoo Model of the record on which the action is triggered; is a void recordset\n# - record: record on which the action is triggered; may be void\n# - records: recordset of all records on which the action is triggered in multi-mode; may be void\n# - time, datetime, dateutil, timezone: useful Python libraries\n# - float_compare: Odoo function to compare floats based on specific precisions\n# - log: log(message, level='info'): logging function to record debug information in ir.logging table\n# - UserError: Warning Exception to use with raise\n# To return an action, assign: action = {...}\n\nfor prod in records:\n for tmp_attr_val in prod.product_template_attribute_value_ids:\n if tmp_attr_val.attribute_id.name == 'Organic':\n #prod.write({'default_code' : env['ir.sequence'].next_by_code('organic_sku') })\n prod.default_code = env['ir.sequence'].next_by_code('organic_sku')": STORE_ATTR

I think it didnt allows the = on the last line

So I replaced it with

prod.write({'default_code' : env['ir.sequence'].next_by_code('organic_sku') })

Unfourtunately it gave this error when the model was 'Product Template':

Error:

Odoo Server Error

Traceback (most recent call last):

File "/home/odoo/src/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch

result = request.dispatch()

File "/home/odoo/src/odoo/odoo/http.py", line 683, in dispatch

result = self._call_function(**self.params)

File "/home/odoo/src/odoo/odoo/http.py", line 359, in _call_function

return checked_call(self.db, *args, **kwargs)

File "/home/odoo/src/odoo/odoo/service/model.py", line 94, in wrapper

return f(dbname, *args, **kwargs)

File "/home/odoo/src/odoo/odoo/http.py", line 347, in checked_call

result = self.endpoint(*a, **kw)

File "/home/odoo/src/odoo/odoo/http.py", line 912, in __call__

return self.method(*args, **kw)

File "/home/odoo/src/odoo/odoo/http.py", line 531, in response_wrap

response = f(*args, **kw)

File "/home/odoo/src/odoo/addons/web/controllers/main.py", line 1745, in run

result = action.run()

File "/home/odoo/src/odoo/odoo/addons/base/models/ir_actions.py", line 632, in run

res = runner(run_self, eval_context=eval_context)

File "/home/odoo/src/odoo/addons/website/models/ir_actions.py", line 61, in _run_action_code_multi

res = super(ServerAction, self)._run_action_code_multi(eval_context)

File "/home/odoo/src/odoo/odoo/addons/base/models/ir_actions.py", line 501, in _run_action_code_multi

safe_eval(self.code.strip(), eval_context, mode="exec", nocopy=True) # nocopy allows to return 'action'

File "/home/odoo/src/odoo/odoo/tools/safe_eval.py", line 346, in safe_eval

raise ValueError('%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr))

Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "/home/odoo/src/odoo/odoo/http.py", line 639, in _handle_exception

return super(JsonRequest, self)._handle_exception(exception)

File "/home/odoo/src/odoo/odoo/http.py", line 315, in _handle_exception

raise exception.with_traceback(None) from new_cause

ValueError: <class 'TypeError'>: "'NoneType' object is not iterable" while evaluating

"# Available variables:\n# - env: Odoo Environment on which the action is triggered\n# - model: Odoo Model of the record on which the action is triggered; is a void recordset\n# - record: record on which the action is triggered; may be void\n# - records: recordset of all records on which the action is triggered in multi-mode; may be void\n# - time, datetime, dateutil, timezone: useful Python libraries\n# - float_compare: Odoo function to compare floats based on specific precisions\n# - log: log(message, level='info'): logging function to record debug information in ir.logging table\n# - UserError: Warning Exception to use with raise\n# To return an action, assign: action = {...}\n\nfor prod in records:\n for tmp_attr_val in prod.product_template_attribute_value_ids:\n if tmp_attr_val.attribute_id.name == 'Organic':\n prod.write({'default_code' : env['ir.sequence'].next_by_code('organic_sku') })\n #prod.default_code = env['ir.sequence'].next_by_code('organic_sku')"

When I used 'Product' as the model nothing happened

What is the soloution?

Thanks for your help!!!

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
Automated Actions: Send Payment Receipt to Customers
automated actions v14 AutomatedActions
Avatar
0
de set. 23
3780
Automated Action on Odoo activity deadline
automated AutomatedActions
Avatar
Avatar
1
de febr. 24
2736
Automated Action sending emails for first time only Solved
automated AutomatedActions
Avatar
Avatar
2
de gen. 24
3113
Create Auto Activity for old customers
v14 AutomatedActions
Avatar
0
d’oct. 21
3205
Automated task creation in sales after make to order production is finished
automated AutomatedActions
Avatar
0
de maig 21
2555
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