Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

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

  • CRM
  • e-Commerce
  • Accounting
  • Inventory
  • PoS
  • Project
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

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

Subscribe

Get notified when there's activity on this post

This question has been flagged
automatedvariantskuv14AutomatedActions
1 Reply
7034 Views
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
Discard
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
Discard
James Camfield
Author

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!

Sign up
Related Posts Replies Views Activity
Automated Actions: Send Payment Receipt to Customers
automated actions v14 AutomatedActions
Avatar
0
Sep 23
3767
Automated Action on Odoo activity deadline
automated AutomatedActions
Avatar
Avatar
1
Feb 24
2724
Automated Action sending emails for first time only Solved
automated AutomatedActions
Avatar
Avatar
2
Jan 24
3099
Create Auto Activity for old customers
v14 AutomatedActions
Avatar
0
Oct 21
3191
Automated task creation in sales after make to order production is finished
automated AutomatedActions
Avatar
0
May 21
2551
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة 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 is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

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