SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
From V7 to V8: The New API
Raphael Collet (rco@odoo.com)
Goal
Make the model API
more object-oriented
more Pythonic
less cluttered
From V7 to V8
compatibility: V7 and V8 APIs are interoperable
·
·
·
·
Agenda
Recordsets
Methods
Environment
Fields
Migrating Modules
·
·
·
·
·
Recordsets
Programming with
Recordsets
A recordsetrecordset is:
an ordered collection of records
one concept to replace
browse records,
browse lists,
browse nulls.
an instance of the model's class
·
·
·
·
·
·
The recordset as a collection
It implements sequence and set operations:
partners == env[['res.partner']]..search([])([])
forfor partner inin partners::
assertassert partner inin partners
printprint partner..name
ifif len((partners)) >=>= 55::
fifth == partners[[44]]
extremes == partners[:[:1010]] ++ partners[[--1010:]:]
union == partners1 || partners2
intersection == partners1 && partners2
difference == partners1 -- partners2
The recordset as a record
It behaves just like former browse records:
printprint partner..name
printprint partner[['name']]
printprint partner..parent_id..company_id..name
Except that updates are written to database:
partner..name == 'Agrolait'
partner..email == 'info@agrolait.com'
partner..parent_id == ...... # another record
The recordset as a record
If len(partners) > 1, do it on the firstfirst record:
printprint partners..name # name of first partner
printprint partners[[00]]..name
partners..name == 'Agrolait' # assign first partner
partners[[00]]..name == 'Agrolait'
If len(partners) == 0, return the null value of the field:
printprint partners..name # False
printprint partners..parent_id # empty recordset
partners..name == 'Foo' # ERROR
The recordset as an instance
Methods of the model's class can be invoked on recordsets:
# calling convention: leave out cr, uid, ids, context
@api.multi@api.multi
defdef write((self,, values):):
result == super((C,, self))..write((values))
# search returns a recordset instead of a list of ids
domain == [([('id',, 'in',, self..ids),), (('parent_id',, '=',, False)])]
roots == self..search((domain))
# modify all records in roots
roots..write({({'modified':: True})})
returnreturn result
The missing parameters are hidden inside the recordset.
Methods
Method decorators
Decorators enable support of bothboth old and new API:
fromfrom odoo importimport Model,, api
classclass stuff((Model):):
@api.model@api.model
defdef create((self,, values):):
# self is a recordset, but its content is unused
......
This method definition is equivalent to:
classclass stuff((Model):):
defdef create((self,, cr,, uid,, values,, context==None):):
# self is not a recordset
......
Method decorators
fromfrom odoo importimport Model,, api
classclass stuff((Model):):
@api.multi@api.multi
defdef write((self,, values):):
# self is a recordset and its content is used
# update self.ids
......
This method definition is equivalent to:
classclass stuff((Model):):
defdef multi((self,, cr,, uid,, ids,, values,, context==None):):
# self is not a recordset
......
Method decorators
One-by-one or "autoloop" decorator:
fromfrom odoo importimport Model,, api
classclass stuff((Model):):
@api.one@api.one
defdef cancel((self):):
self..state == 'cancel'
When invoked, the method is applied on every record:
recs..cancel()() # [rec.cancel() for rec in recs]
Method decorators
Methods that return a recordset instead of ids:
fromfrom odoo importimport Model,, api
classclass stuff((Model):):
@api.multi@api.multi
@api.returns@api.returns(('res.partner'))
defdef root_partner((self):):
p == self..partner_id
whilewhile p..parent_id::
p == p..parent_id
returnreturn p
When called with the old API, it returns ids:
roots == recs..root_partner()()
root_ids == model..root_partner((cr,, uid,, ids,, context==None))
Environment: cr, uid, context
The environment object
Encapsulates cr, uid, context:
# recs.env encapsulates cr, uid, context
recs..env..cr # shortcut: recs._cr
recs..env..uid # shortcut: recs._uid
recs..env..context # shortcut: recs._context
# recs.env also provides helpers
recs..env..user # uid as a record
recs..env..ref(('base.group_user')) # resolve xml id
recs..env[['res.partner']] # access to new-API model
The environment object
Switching environments:
# rebrowse recs with different parameters
env2 == recs..env((cr2,, uid2,, context2))
recs2 == recs..with_env((env2))
# special case: change/extend the context
recs2 == recs..with_context((context2))
recs2 == recs..with_context((lang=='fr')) # kwargs extend current context
# special case: change the uid
recs2 == recs..sudo((user))
recs2 == recs..sudo()() # uid = SUPERUSER_ID
Fields
Fields as descriptors
Python descriptors provide getter/setter (like property):
fromfrom odoo importimport Model,, fields
classclass res_partner((Model):):
_name == 'res.partner'
name == fields..Char((required==True))
parent_id == fields..Many2one(('res.partner',, string=='Parent'))
Computed fields
Regular fields with the name of the compute method:
classclass res_partner((Model):):
......
display_name == fields..Char((
string=='Name',, compute=='_compute_display_name',,
))
@api.one@api.one
@api.depends@api.depends(('name',, 'parent_id.name'))
defdef _compute_display_name((self):):
names == [[self..parent_id..name,, self..name]]
self..display_name == ' / '..join((filter((None,, names))))
Computed fields
The compute method must assign field(s) on records:
untaxed == fields..Float((compute=='_amounts'))
taxes == fields..Float((compute=='_amounts'))
total == fields..Float((compute=='_amounts'))
@api.multi@api.multi
@api.depends@api.depends(('lines.amount',, 'lines.taxes'))
defdef _amounts((self):):
forfor order inin self::
order..untaxed == sum((line..amount forfor line inin order..lines))
order..taxes == sum((line..taxes forfor line inin order..lines))
order..total == order..untaxed ++ order..taxes
Computed fields
Stored computed fields are much easier now:
display_name == fields..Char((
string=='Name',, compute=='_compute_display_name',, store==True,,
))
@api.one@api.one
@api.depends@api.depends(('name',, 'parent_id.name'))
defdef _compute_display_name((self):):
......
Field dependencies (@depends) are used for
cache invalidation,
recomputation,
onchange.
·
·
·
Fields with inverse
On may also provide inverseinverse and searchsearch methods:
classclass stuff((Model):):
name == fields..Char()()
loud == fields..Char((
store==False,, compute=='_compute_loud',,
inverse=='_inverse_loud',, search=='_search_loud',,
))
@api.one@api.one
@api.depends@api.depends(('name'))
defdef _compute_loud((self):):
self..loud == ((self..name oror ''))..upper()()
......
Fields with inverse
classclass stuff((Model):):
name == fields..Char()()
loud == fields..Char((
store==False,, compute=='_compute_loud',,
inverse=='_inverse_loud',, search=='_search_loud',,
))
......
@api.one@api.one
defdef _inverse_loud((self):):
self..name == ((self..loud oror ''))..lower()()
defdef _search_loud((self,, operator,, value):):
ifif value isis notnot False::
value == value..lower()()
returnreturn [([('name',, operator,, value)])]
Onchange methods
For computed fields: nothing to do!nothing to do!
For other fields: API is similar to compute methods:
@api.onchange@api.onchange(('partner_id'))
defdef _onchange_partner((self):):
ifif self..partner_id::
self..delivery_id == self..partner_id
The record self is a virtual record:
all form values are set on self
assigned values are not written to database but
returned to the client
·
·
Onchange methods
A field element on a form is automaticallyautomatically decorated with
on_change="1":
if it has an onchange method
if it is a dependency of a computed field
This mechanism may be prevented by explicitly decorating
a field element with on_change="0".
·
·
Python constraints
Similar API, with a specific decorator:
@api.one@api.one
@api.constrains@api.constrains(('lines',, 'max_lines'))
defdef _check_size((self):):
ifif len((self..lines)) >> self..max_lines::
raiseraise WarningWarning((_(("Too many lines in %s")) %% self..name))
The error message is provided by the exception.
Migrating Modules
Guidelines
Do the migration step-by-step:
1. migrate field definitions
rewrite compute methods
2. migrate methods
rely on interoperability
use decorators, they are necessary
3. rewrite onchange methods (incompatible API)
beware of overridden methods!
·
·
·
·
From V7 to V8: The New API
Thanks!

Mais conteúdo relacionado

Mais procurados

C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shortingargusacademy
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeManoj Kumar
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Philip Schwarz
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Roel Hartman
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type ClassesJohn De Goes
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureOdoo
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsOluwaleke Fakorede
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de donnéesRomain Lecomte
 

Mais procurados (20)

02 arrays
02 arrays02 arrays
02 arrays
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
C Prog - Array
C Prog - ArrayC Prog - Array
C Prog - Array
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
Arrays matrix 2020 ab
Arrays matrix 2020 abArrays matrix 2020 ab
Arrays matrix 2020 ab
 
R-Shiny Cheat sheet
R-Shiny Cheat sheetR-Shiny Cheat sheet
R-Shiny Cheat sheet
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 

Semelhante a Odoo from 7.0 to 8.0 API

Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 DatasourceKaz Watanabe
 
Method and decorator
Method and decoratorMethod and decorator
Method and decoratorCeline George
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsRefactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsTristan Gomez
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA clientMr. Vengineer
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxParveenShaik21
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonManageIQ
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationBartosz Konieczny
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
Webinar - Office 365 & PowerShell : A Match Made in Heaven
Webinar - Office 365 & PowerShell : A Match Made in HeavenWebinar - Office 365 & PowerShell : A Match Made in Heaven
Webinar - Office 365 & PowerShell : A Match Made in HeavenSébastien Levert
 

Semelhante a Odoo from 7.0 to 8.0 API (20)

Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
 
Method and decorator
Method and decoratorMethod and decorator
Method and decorator
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsRefactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and Patterns
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA client
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron Patterson
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
Webinar - Office 365 & PowerShell : A Match Made in Heaven
Webinar - Office 365 & PowerShell : A Match Made in HeavenWebinar - Office 365 & PowerShell : A Match Made in Heaven
Webinar - Office 365 & PowerShell : A Match Made in Heaven
 
Elastic tire demo
Elastic tire demoElastic tire demo
Elastic tire demo
 

Último

Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 

Último (20)

Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

Odoo from 7.0 to 8.0 API

  • 1. From V7 to V8: The New API Raphael Collet (rco@odoo.com)
  • 2. Goal Make the model API more object-oriented more Pythonic less cluttered From V7 to V8 compatibility: V7 and V8 APIs are interoperable · · · ·
  • 5. Programming with Recordsets A recordsetrecordset is: an ordered collection of records one concept to replace browse records, browse lists, browse nulls. an instance of the model's class · · · · · ·
  • 6. The recordset as a collection It implements sequence and set operations: partners == env[['res.partner']]..search([])([]) forfor partner inin partners:: assertassert partner inin partners printprint partner..name ifif len((partners)) >=>= 55:: fifth == partners[[44]] extremes == partners[:[:1010]] ++ partners[[--1010:]:] union == partners1 || partners2 intersection == partners1 && partners2 difference == partners1 -- partners2
  • 7. The recordset as a record It behaves just like former browse records: printprint partner..name printprint partner[['name']] printprint partner..parent_id..company_id..name Except that updates are written to database: partner..name == 'Agrolait' partner..email == 'info@agrolait.com' partner..parent_id == ...... # another record
  • 8. The recordset as a record If len(partners) > 1, do it on the firstfirst record: printprint partners..name # name of first partner printprint partners[[00]]..name partners..name == 'Agrolait' # assign first partner partners[[00]]..name == 'Agrolait' If len(partners) == 0, return the null value of the field: printprint partners..name # False printprint partners..parent_id # empty recordset partners..name == 'Foo' # ERROR
  • 9. The recordset as an instance Methods of the model's class can be invoked on recordsets: # calling convention: leave out cr, uid, ids, context @api.multi@api.multi defdef write((self,, values):): result == super((C,, self))..write((values)) # search returns a recordset instead of a list of ids domain == [([('id',, 'in',, self..ids),), (('parent_id',, '=',, False)])] roots == self..search((domain)) # modify all records in roots roots..write({({'modified':: True})}) returnreturn result The missing parameters are hidden inside the recordset.
  • 11. Method decorators Decorators enable support of bothboth old and new API: fromfrom odoo importimport Model,, api classclass stuff((Model):): @api.model@api.model defdef create((self,, values):): # self is a recordset, but its content is unused ...... This method definition is equivalent to: classclass stuff((Model):): defdef create((self,, cr,, uid,, values,, context==None):): # self is not a recordset ......
  • 12. Method decorators fromfrom odoo importimport Model,, api classclass stuff((Model):): @api.multi@api.multi defdef write((self,, values):): # self is a recordset and its content is used # update self.ids ...... This method definition is equivalent to: classclass stuff((Model):): defdef multi((self,, cr,, uid,, ids,, values,, context==None):): # self is not a recordset ......
  • 13. Method decorators One-by-one or "autoloop" decorator: fromfrom odoo importimport Model,, api classclass stuff((Model):): @api.one@api.one defdef cancel((self):): self..state == 'cancel' When invoked, the method is applied on every record: recs..cancel()() # [rec.cancel() for rec in recs]
  • 14. Method decorators Methods that return a recordset instead of ids: fromfrom odoo importimport Model,, api classclass stuff((Model):): @api.multi@api.multi @api.returns@api.returns(('res.partner')) defdef root_partner((self):): p == self..partner_id whilewhile p..parent_id:: p == p..parent_id returnreturn p When called with the old API, it returns ids: roots == recs..root_partner()() root_ids == model..root_partner((cr,, uid,, ids,, context==None))
  • 16. The environment object Encapsulates cr, uid, context: # recs.env encapsulates cr, uid, context recs..env..cr # shortcut: recs._cr recs..env..uid # shortcut: recs._uid recs..env..context # shortcut: recs._context # recs.env also provides helpers recs..env..user # uid as a record recs..env..ref(('base.group_user')) # resolve xml id recs..env[['res.partner']] # access to new-API model
  • 17. The environment object Switching environments: # rebrowse recs with different parameters env2 == recs..env((cr2,, uid2,, context2)) recs2 == recs..with_env((env2)) # special case: change/extend the context recs2 == recs..with_context((context2)) recs2 == recs..with_context((lang=='fr')) # kwargs extend current context # special case: change the uid recs2 == recs..sudo((user)) recs2 == recs..sudo()() # uid = SUPERUSER_ID
  • 19. Fields as descriptors Python descriptors provide getter/setter (like property): fromfrom odoo importimport Model,, fields classclass res_partner((Model):): _name == 'res.partner' name == fields..Char((required==True)) parent_id == fields..Many2one(('res.partner',, string=='Parent'))
  • 20. Computed fields Regular fields with the name of the compute method: classclass res_partner((Model):): ...... display_name == fields..Char(( string=='Name',, compute=='_compute_display_name',, )) @api.one@api.one @api.depends@api.depends(('name',, 'parent_id.name')) defdef _compute_display_name((self):): names == [[self..parent_id..name,, self..name]] self..display_name == ' / '..join((filter((None,, names))))
  • 21. Computed fields The compute method must assign field(s) on records: untaxed == fields..Float((compute=='_amounts')) taxes == fields..Float((compute=='_amounts')) total == fields..Float((compute=='_amounts')) @api.multi@api.multi @api.depends@api.depends(('lines.amount',, 'lines.taxes')) defdef _amounts((self):): forfor order inin self:: order..untaxed == sum((line..amount forfor line inin order..lines)) order..taxes == sum((line..taxes forfor line inin order..lines)) order..total == order..untaxed ++ order..taxes
  • 22. Computed fields Stored computed fields are much easier now: display_name == fields..Char(( string=='Name',, compute=='_compute_display_name',, store==True,, )) @api.one@api.one @api.depends@api.depends(('name',, 'parent_id.name')) defdef _compute_display_name((self):): ...... Field dependencies (@depends) are used for cache invalidation, recomputation, onchange. · · ·
  • 23. Fields with inverse On may also provide inverseinverse and searchsearch methods: classclass stuff((Model):): name == fields..Char()() loud == fields..Char(( store==False,, compute=='_compute_loud',, inverse=='_inverse_loud',, search=='_search_loud',, )) @api.one@api.one @api.depends@api.depends(('name')) defdef _compute_loud((self):): self..loud == ((self..name oror ''))..upper()() ......
  • 24. Fields with inverse classclass stuff((Model):): name == fields..Char()() loud == fields..Char(( store==False,, compute=='_compute_loud',, inverse=='_inverse_loud',, search=='_search_loud',, )) ...... @api.one@api.one defdef _inverse_loud((self):): self..name == ((self..loud oror ''))..lower()() defdef _search_loud((self,, operator,, value):): ifif value isis notnot False:: value == value..lower()() returnreturn [([('name',, operator,, value)])]
  • 25. Onchange methods For computed fields: nothing to do!nothing to do! For other fields: API is similar to compute methods: @api.onchange@api.onchange(('partner_id')) defdef _onchange_partner((self):): ifif self..partner_id:: self..delivery_id == self..partner_id The record self is a virtual record: all form values are set on self assigned values are not written to database but returned to the client · ·
  • 26. Onchange methods A field element on a form is automaticallyautomatically decorated with on_change="1": if it has an onchange method if it is a dependency of a computed field This mechanism may be prevented by explicitly decorating a field element with on_change="0". · ·
  • 27. Python constraints Similar API, with a specific decorator: @api.one@api.one @api.constrains@api.constrains(('lines',, 'max_lines')) defdef _check_size((self):): ifif len((self..lines)) >> self..max_lines:: raiseraise WarningWarning((_(("Too many lines in %s")) %% self..name)) The error message is provided by the exception.
  • 29. Guidelines Do the migration step-by-step: 1. migrate field definitions rewrite compute methods 2. migrate methods rely on interoperability use decorators, they are necessary 3. rewrite onchange methods (incompatible API) beware of overridden methods! · · · ·
  • 30. From V7 to V8: The New API Thanks!