Models#
Model#
- class trytond.model.Model([id[, \**kwargs]])#
The base class that every kind of model inherits.
Class attributes are:
- Model.__name__#
The a unique name to reference the model throughout the platform.
- Model.__access__#
A set that contains the names of relation field for which the access rights are also checked for this model.
- Model.__queue__#
Return a queue caller for the model. The called method will be pushed into the queue.
- Model._record#
The record class to store internaly the values of the instances.
- Model._defaults#
A dictionary with the field name as key and its default method as value.
Class methods:
- classmethod Model.__setup__()#
Setup the class before adding into the
Pool. Seetrytond.pool.PoolBase.__setup__().
- classmethod Model.__post_setup__()#
Setup the class after added into the
Pool. Seetrytond.pool.PoolBase.__post_setup__().
- classmethod Model.__register__(module_name)#
Register the model in Model and Model Field. See
trytond.pool.PoolBase.__register__().
- classmethod Model.default_get([fields_names[[, with_rec_name], with_default]])#
Return a dictionary with the default values for each field in
fields_namesor all fields if not specified. Default values are defined by the returned value of each class method with the patterndefault_<field name>().with_rec_nameallow to addrec_namevalue for eachMany2One,One2One,Referencefield.with_defaultallows to not use the value from thedefault_<field name>methods.The
default_rec_namekey in the context can be used to define the value of the_rec_namefield.The
default_<field name>keys in the context can be used to define the value of the field.
- classmethod Model.fields_get([fields_names[, level]])#
Return the definition of each field on the model.
leveldefines the number of relations to include in the relation field definition.
- classmethod Model.__names__([field[, record]])#
Return a dictionary with the name of the
model, thefieldand therecordand thevalueof the field. It is a convenience-method used to format messages which should include those names.
Instance methods:
- Model.pre_validate()#
Validate the instance before being stored. This method is called by the client to validate the instance.
ModelView#
- class trytond.model.ModelView#
Add the requirements to display the record in a view.
Class attributes:
- ModelView._buttons#
A dictionary with button name as key and the states dictionary for the button. The keys are
invisible,readonlyandiconwhich have aPYSONstatement as value anddependswhich has a list of field names on which the states depend. This is used as default attributes of the buttons for the views that show them.
Static methods:
- static ModelView.button()#
Decorate button’s method to check group access and rule.
- static ModelView.button_action(action)#
Same as
button()but return the id of the XML id action or the action value updated by the returned value of the method.
- static ModelView.button_change([\*fields[, methods]])#
Same as
button()but for button that change values of the fields on client side (similar to on_change).methodscan be used to duplicate the field names from other decorated methods. This is useful if the decorated method calls another method.Note
Only on instance methods.
Class methods:
- classmethod ModelView.fields_view_get([view_id[, view_type[, level]]])#
Return a view definition used by the client. The definition is:
{ 'model': model name, 'type': view type, 'view_id': view id, 'arch': XML description, 'fields': { field name: { ... }, }, 'field_childs': field for tree, }
- classmethod ModelView.view_toolbar_get()#
Returns the model specific actions and exports in a dictionary with keys:
printa list of available reports.
actiona list of available actions.
relatea list of available relations.
exportsa list of available exports.
- classmethod ModelView.view_attributes()#
Returns a list of XPath, attribute, value and an optional depends list. Each element from the XPath will get the attribute set with the JSON encoded value. If the depends list is set its fields are added to the view if the xpath matches at least one element.
Note
The
view_idis set to thecontextwhen this method is called.
- classmethod ModelView.parse_view(tree, type[, view_id[, field_children[, level[, view_depends]]]])#
Return the sanitized XML and the corresponding fields definition.
Note
This method is public mainly to allow modification the existing XML of the view by code.
Instance methods:
- ModelView._changed_values()#
Return the values changed since the instantiation. By default, the value of a field is its internal representation except:
for
Referencefield: the string ‘<model name>,<record id>’.for
One2ManyandMany2Many: a dictionary composed of three keys:add: a list of tuple, the first element is the index where the new line is added, the second element is default values.update: a list of dictionary of changed values including theid.remove: a list of ids.
- ModelView.on_change(fieldnames)#
Return the list of changes by calling
on_changemethod of each field.
- ModelView.on_change_with(fieldnames)#
Return the new values of all fields by calling
on_change_withmethod of each field.
- ModelView.on_change_notify(fieldnames)#
Returns a list of type and message couple to display on the client side. Available types are
info,warninganderror.Note
To be called by the client, this method must be decorated by
depends()with the fields needed.
- ModelView.on_scan_code(code)#
Modify the instance when
codeis scanned. If the instance is not modified the scan loop ends.Note
When extended, this method must be decorated by
depends()with the fields used.
- ModelView.autocomplete(text[, domain[, limit[, order]]])#
Return a list of dictionary for records completing
text. The dictionary is composed ofid,nameanddefaults.The client call this method to provide completion.
Note
The
defaultsis used whenidis empty to get the default values for the record to create.
ModelStorage#
- class trytond.model.ModelStorage#
Add storage capability of record.
Class attributes are:
- ModelStorage.create_uid#
The definition of the
Many2Onefield that points to the user who created the record.
- ModelStorage.create_date#
The definition of the
Timestampfield that stores the creation time of the record.
- ModelStorage.write_uid#
The definition of the
Many2Onefield that points to the last user who modified the record.
- ModelStorage.write_date#
The definition of the
Timestampfield that stored the last modification time of the record.
Instance attributes are:
- ModelStorage._transaction#
The
Transactioninstance under which the record was instantiated.
- ModelStorage._user#
The User id from the
_transaction.
Static methods:
- static ModelStorage.default_create_uid()#
Return the default value for
create_uid.
- static ModelStorage.default_create_date()#
Return the default value for
create_date.
Class methods:
- classmethod ModelStorage.log(records, event[, target[, user[, \**extra]]])#
Log event for records.
- classmethod ModelStorage.preprocess_values(cls, mode, values)#
Returns a copy of
valuesto be used forcreate()andwrite().modeis eithercreateorwrite.
- classmethod ModelStorage.create(vlist)#
Create records.
vlistis list of dictionaries with fields names as key and created values as value and return the list of new instances.
- classmethod ModelStorage.read(ids, fields_names)#
Return a list of dictionary for the record ids. The dictionary is composed of the fields as key and their values.
fields_namescan contain dereferenced fields from related models. Their values will be returned under the referencing field suffixed by a.. The number of dots in the name is not limited. The number of records read using dots can be limited with therelated_read_limitkey in the context. The remaining records will only contain theidfield.fields_namescan also contain<field>:stringforSelectionorMultiSelectionfields. Their human-readable value are returned.The virtual fields
_writeand_deletecan be used the read the writeable and deleteable state of the records. Regarding the_timestampvirtual fields it contains a timestamp that is used in the context to make a soft lock preventing update collisions.Note
The order of the returned list is not guaranteed.
- classmethod ModelStorage.index_get_field(name)#
Return the index to order of the calls to field get.
- classmethod ModelStorage.write(records, values[[, records, values], ...])#
Write
valueson the list of records.valuesis a dictionary with fields names as key and writen values as value.
- classmethod ModelStorage.index_set_field(name)#
Return the index to order of the calls to field set.
- classmethod ModelStorage.delete(records)#
Delete records.
- classmethod ModelStorage.check_modification(mode, record[, values[, external]])#
Method called after
recordsare created and beforerecordsare modified withvaluesor deleted.externalspecifies whether remote access check must be enforced.Note
It is used to prevent some kind of modification by raising an
AccessError.
- classmethod ModelStorage.on_modification(mode, records[, field_names])#
Method called after
recordshave been modified.modecan be eithercreate,writeordelete. When themodeiswrite,field_namesis asetcontaining modified fields.Note
It is used to trigger actions based on what has been modified.
- ModelStorage.on_write(records, values):
Returns a list of methods to call once the records have been modified.
valuesis a dictionary with fields names as key and writen values as value.
- classmethod ModelStorage.on_delete(records)#
Returns a list of methods to call once the records have been deleted.
- classmethod ModelStorage.copy(records[, default])#
Duplicate the records.
defaultis a dictionary of default value per field name for the created records.The values of
defaultmay be also callable that take a dictionary containing the fields and values of the record copied and return of the value.The keys of
defaultmay use the dotted notation for theOne2Manyto define the default to pass to itscopyoperation.New records are returned following the input order.
Note
The
One2ManyandMany2Manyrelation fields are not copied if theirreadonlyattribute isTrueor if their relationionalModelis not aModelStorageor if it has aModelSQL.table_query().
- classmethod ModelStorage.search(domain[, offset[, limit[, order[, count]]]])#
Return a list of records that match the domain.
If
offsetorlimitare set, the result starts at the offset and has the length of the limit.The
orderis a list of tuples defining the order of the result:[ ('field name', 'ASC'), ('other field name', 'DESC'), ... ]The first element of the tuple is a field name of the model and the second is the sort ordering as
ASCfor ascending,DESCfor descending or empty for a default order. This second element may containNULLS FIRSTorNULLS LASTto sort null values before or after non-null values. If neither is specified the default behavior of the backend is used.In case the field used is a
Many2One, it is also possible to use the dotted notation to sort on a specific field from the target record. Or for aDictfield, the dotted notation is used to sort on the key’s value.If
countis set toTrue, then the result is the number of records. The count result is limited upto the value oflimitif set.
- classmethod ModelStorage.search_count(domain[, offset[, limit]])#
Return the number of records that match the domain.
The result is limited upto the value of
limitif set and reduced by offset.
- classmethod ModelStorage.search_read(domain[, offset[, limit[, order[, fields_names]]]])#
Call
search()andread()at once.Useful for the client to reduce the number of calls.
- classmethod ModelStorage.search_global(cls, text)#
Yield tuples (record, name, icon) for records matching text.
It is used for the global search.
- classmethod ModelStorage.estimated_count()#
Return an estimation of the number of records stored.
- classmethod ModelStorage.browse(ids)#
Return a list of record instance for the
ids.
- classmethod ModelStorage.export_data(records, fields_names[, header])#
Return a list of list of values for each
records.The list of values follows
fields_names. The result includes the description of the fields ifheaderis set.Relational fields are defined with
/at any depth.Descriptor on fields are available by appending
.and the name of the method on the field that returns the descriptor.
- classmethod ModelStorage.export_data_domain(domain, fields_names[, offset[, limit[, order[, header]]]])#
Call
search()andexport_data()together.Useful for the client to reduce the number of calls and the data transfered.
- classmethod ModelStorage.import_data(fields_names, data)#
Create or update records for all values in
data.The field names of values must be defined in
fields_names. It returns the number of imported records.
- classmethod ModelStorage.compute_fields(record[, field_names])#
Returns a dictionary of values to be stored if any field of
field_nameshas been modified.
- classmethod ModelStorage.validate(records)#
Validate the integrity of records after creation and modification.
This method must be overridden to add validation and must raise an
ValidationErrorif validation fails.
- classmethod ModelStorage.validate_fields(records, field_names)#
Validate the integrity of records after modification of the fields. This method must be overridden to add validation for the field names set and must raise an exception if validation fails.
Dual methods:
- classmethod ModelStorage.save(records)#
Save the modification made on the records.
Warning
Fields that have a container as a value must be reassigned to the parent record in order to be saved when the parent record is saved.
Instance methods:
- ModelStorage._save_values()#
Returns the modified values from the saved one, which can be used with
create()orwrite().
- ModelStorage.resources()#
Return a dictionary with the number of attachments (
attachment_count), notes (note_count) and unread note (note_unread).
ModelSQL#
- class trytond.model.ModelSQL#
Implement ModelStorage for an SQL database.
Class attributes are:
- ModelSQL._table#
The name of the database table which is mapped to the class.
If not set, the value of
__name__is used with dots converted to underscores.
- ModelSQL._order_name#
The name of the field on which the records must be sorted when sorting on a field refering to the model.
If not set,
_rec_nameis used.
- ModelSQL._history#
If true, all changes on records are stored in an history table.
- ModelSQL._sql_constraints#
A list of SQL constraints that are added on the table:
[ (<constraint name>, <constraint>, <xml id>), ... ]
- constraint name
The name of the SQL constraint in the database.
- constraint
An instance of
Constraint- xml id
The message id for
gettext()
Class methods:
- classmethod ModelSQL.__setup_indexes__()#
Setup the
_sql_indexesbefore creating them on the table.Note
The method is called only once when all the models have been setup by the
Pool.
- classmethod ModelSQL.__table__()#
Return a SQL Table instance for the Model.
- classmethod ModelSQL.__table_history__()#
Return a SQL Table instance for the history of Model.
- classmethod ModelSQL.__table_handler__([module_name[, history]])#
Return a
TableHandlerinstance for the Model.
- classmethod ModelSQL.table_query()#
Could be defined to use a custom SQL query instead of a table of the database. It should return a SQL FromItem with a column
idwith a unique value and a column for each field except forcreate_uid,create_date,write_uidandwrite_date.
- classmethod ModelSQL.history_revisions(ids)#
Return a sorted list of all revisions for ids.
The list is composed of the date, id and username of the revision.
- classmethod ModelSQL.restore_history(ids, datetime)#
Restore the record ids from history at the specified date time.
Restoring a record still generates an entry in the history table.
Warning
No access rights are verified, the restored records are not validated and no triggers are called.
- classmethod ModelSQL.restore_history_before(ids, datetime)#
Restore the record ids from history before the specified date time.
Restoring a record still generates an entry in the history table.
Warning
No access rights are verified, the restored records are not validated and not triggers are called.
- classmethod ModelSQL.search(domain[, offset[, limit[, order[, count[, query]]]]])#
Same as
ModelStorage.search()with the additionalqueryargument. Thedomainis converted bysearch_domain().If
queryis set toTrue, the the result is the SQL query.
- classmethod ModelSQL.search_domain(domain[, active_test[, tables]])#
Convert a domain into a SQL expression by returning the updated tables dictionary and a SQL expression.
If
active_testis set toFalse, no clause againstDeactivableMixin.activefield is added to the domain.Where
tablesis a nested dictionary containing the existing joins:{ None: (<Table invoice>, None), 'party': { None: (<Table party>, <join_on sql expression>), 'addresses': { None: (<Table address>, <join_on sql expression>), }, }, }
Dual methods:
- classmethod ModelSQL.lock([records])#
Take a lock for update on the records or take a lock on the whole table.
Constraint#
- class trytond.model.Constraint(table)#
Represent a SQL constraint for the table.
Instance attributes:
- Constraint.table#
The SQL Table on which the constraint is defined.
Check#
- class trytond.model.Check(table, expression)#
Represent a check Constraint which enforce the validity of the
expression.
Instance attributes:
- Check.expression#
The SQL expression to check.
Unique#
- class trytond.model.Unique(table, \*columns)#
Represent a unique Constraint which enforce the uniqueness of the
group of columns.
Instance attributes:
- Unique.columns#
The tuple of SQL Column instances.
- Unique.operators#
The tuple of
Equaloperators.
Exclude#
- class trytond.model.Exclude(table[, (expression, operator), ...[, where]])#
Represent an exclude Constraint which guarantees that if any two rows
are compared on the specified expression using the specified operator not all
of these comparisons will return TRUE.
Instance attributes:
- Exclude.excludes#
The tuple of expression and operator.
- Exclude.columns#
The tuple of expressions.
- Exclude.operators#
The tuple of operators.
- Exclude.where#
The clause for which the exclusion applies.
Index#
- class trytond.model.Index(table[, \*expressions[, \*\*options]])#
Represent a SQL index for the table for the sequence of expressions.
An expression is a tuple of SQL expression and a
Usage.
Available options are:
include: a list of columns to include in the index
where: the where clause for partial index
- Index.Unaccent(expression)#
Apply unaccent function if the database supports it.
- Index.Usage([cardinality[, \*\*options]])#
Represent a usage of a SQL expression.
Available cardinality is low, normal (default) and high.
Available options are:
collation: the name of the collation
order: the sort order
- Index.Equality([cardinality[, \*\*options]])#
Represent an equality usage.
- Index.Range([cardinality[, \*\*options]])#
Represent an range usage.
- Index.Similarity([cardinality[, \*\*options]])#
Represent a similar usage only for text. Additional options are available:
begin: optimize for constant pattern and anchored to the beginning of the string
convert_from#
- trytond.model.convert_from(table, tables[, type_])#
Return a SQL FromItem constructed by joining table and tables using type_ with default value LEFT.
Workflow#
- class trytond.model.Workflow#
A mixin to handle transition check.
Class attribute:
- Workflow._transition_state#
The name of the field that will be used to check state transition. The default value is ‘state’.
- Workflow._transitions#
A set containing tuples of from and to state.
Static methods:
- static Workflow.transition(state)#
Decorate method to filter records for which the transition is valid and finally to update the state of the filtered record.
ModelSingleton#
- class trytond.model.ModelSingleton#
Modify ModelStorage into a singleton.
This means that there will be only one record of this model.
It is commonly used to store configuration value.
Class methods:
- classmethod ModelSingleton.get_singleton()#
Return the instance of the unique record if there is one.
DictSchemaMixin#
- class trytond.model.DictSchemaMixin#
A mixin for the schema of Dict field.
Class attributes are:
- DictSchemaMixin.type\_
The
Selectionfield for the type of the key.The available types are:
boolean
integer
char
color
float
numeric
date
datetime
selection
- DictSchemaMixin.domain#
A domain constraint on the dictionary key that will be enforced only on the client side.
The key must be referenced by its name in the left operator of the domain. The PYSON evaluation context used to compute the domain is the dictionary value. Likewise the domain is tested using the dictionary value.
- DictSchemaMixin.selection#
The
Textfield to store the couple of key and label when the type isselection.The format is a key/label separated by “:” per line.
Static methods:
Class methods:
- classmethod DictSchemaMixin.get_keys(records)#
Return the definition of the keys for the records.
- classmethod DictSchemaMixin.get_relation_fields()#
Return a dictionary with the field definition of all the keys like the result of
Model.fields_get().It is possible to disable this method (returns an empty dictionary) by setting in the
dictsection of the configuration, theModel.__name__toFalse.
Instance methods:
- DictSchemaMixin.get_selection_json(name)#
getterfor theselection_json.
- DictSchemaMixin.format(value[, lang])#
Format the value using the key definition and the language.
MatchMixin#
- class trytond.model.MatchMixin#
A mixin to add to a Model a match method on pattern.
The pattern is a dictionary with field name as key and the value to compare.
The record matches the pattern if for all dictionary entries, the value of the
record is equal or not defined.
Instance methods:
- MatchMixin.match(pattern[, match_none])#
Return if the instance match the pattern.
If
match_noneis setNonevalue of the instance will be compared.
UnionMixin#
- class trytond.model.UnionMixin#
A mixin to create a ModelSQL which is the UNION of some
ModelSQL’s. The ids of each models are sharded to be unique.
Static methods:
Class methods:
- classmethod UnionMixin.union_shard(column, model)#
Return a SQL expression that shards the column containing record id of model name.
- classmethod UnionMixin.union_unshard(record_id)#
Return the original instance of the record for the sharded id.
- classmethod UnionMixin.union_column(name, field, table, Model)#
Return the SQL column that corresponds to the field on the union model.
- classmethod UnionMixin.union_columns(model)#
Return the SQL table and columns to use for the UNION for the model name.
SymbolMixin#
- class trytond.model.SymbolMixin#
A mixin to manage the display of symbols on the client side.
Instance methods:
- SymbolMixin.get_symbol(sign[, symbol])#
Return a symbol and its position.
The position indicates whether the symbol should appear before (0) or after (1) the value. If no symbol parameter is supplied then the mixin uses the value of attribute named
symbol.
DigitsMixin#
- class trytond.model.DigitsMixin#
A mixin to manage the digits of fields.Float.digits and
fields.Numeric.digits from a Model.
Instance methods:
- DigitsMixin.get_digits()#
Return a tuple of two integers to use a
digitsattribute.
sequence_ordered#
- trytond.model.sequence_ordered([field_name[, field_label[, order]]])#
Return a mixin class which defines the order of a ModelSQL with an
Integer field.
field_name indicates the name of the field to be created and its default
values is sequence.
field_label defines the label which will be used by the field and defaults
to Sequence.
Order specifies the order direction and defaults to ASC NULLS FIRST.
sort#
- trytond.model.sort(records, order)#
Return a new list of records ordered by the order list defined like in
search().
sequence_reorder#
- trytond.model.sequence_reorder(records[, field_name])#
Updates the sequence
field_nameto follow the current order of the records. Returns the list of records.
MultiValueMixin#
- class trytond.model.MultiValueMixin#
A mixin for Model to help having MultiValue fields
with multi-values on a ValueMixin.
The values are stored by creating one record per pattern.
The patterns are the same as those on MatchMixin.
Class methods:
- classmethod MultiValueMixin.multivalue_model(field)#
Return the
ValueMixinon which the values are stored for the field name.The default is class name suffixed by the field name.
- classmethod MultiValueMixin.setter_multivalue(records, name, value, \*\*pattern)#
gettermethod for thetrytond.model.fields.Functionfields.
Instance methods:
- MultiValueMixin.multivalue_records(field)#
Return the list of all
ValueMixinrecords linked to the instance.By default, it returns the value of the first found
One2Manylinked to the multivalue model or all the records of this one.
- MultiValueMixin.multivalue_record(field, \*\*pattern)#
Return a new record of
ValueMixinlinked to the instance.
- MultiValueMixin.get_multivalue(name, \*\*pattern)#
Return the value of the field
namefor the pattern.
- MultiValueMixin.set_multivalue(name, value, [save, ]\*\*pattern)#
Store the value of the field
namefor the pattern.If
saveis true, it will be stored in the database, otherwise the modifiedValueMixinrecords are returned unsaved.saveis true by default.
Warning
To customize the pattern, both methods must be override the same way.
ValueMixin#
- class trytond.model.ValueMixin#
A mixin to store the values of MultiValueMixin.
DeactivableMixin#
- class trytond.model.DeactivableMixin#
A mixin to add soft deletion to the model. It renders all the fields as read-only when the record is inactive.
Class attributes are:
- DeactivableMixin.active#
The definition of the
trytond.model.fields.Booleanfield to store soft deletion state.False values is considered as soft deletion.
tree#
- trytond.model.tree([parent[, name[, separator]]])#
Return a mixin class TreeMixin.
parent indicates the name of the field that defines the parent of the tree
and its default value is parent.
name indicates the name of the field that defines the name of the record and
its default value is name.
If separator is set, the get_rec_name() constructs the
name by concatenating each parent names using it as separator and
search_rec_name() is adapted to search across the tree.
- class trytond.model.TreeMixin#
- classmethod TreeMixin.check_recursion(records)#
Helper method that checks if there is no recursion in the tree defined by
tree().
- trytond.model.sum_tree(records, values[, parent])#
Helper method to sum
valuesfollowing uprecordstree usingparent.recordsmust contain a complete branch of the tree.valuesis a dictionary with record id as key.
avatar_mixin#
- trytond.model.avatar_mixin([size[, default]])#
Return a mixin AvatarMixin.
size defines the size of the avatar image and its default value is 64.
default indicates the name of the field to use for generating a default
avatar, if it’s not set then no default avatar is generated.
- class trytond.model.AvatarMixin#
- AvatarMixin.has_avatar#
Indicate whether the record has an avatar.
- classmethod AvatarMixin.generate_avatar(records, field)#
Generate a default avatar for each record using the field.