How it works...

To create a new record for a model, we can call the create(values) method on any recordset related to the model. This method returns a new recordset of a length of 1 and contains the new record, with the field values specified in the values dictionary.

In the dictionary, the keys give the name of the fields, and the corresponding values correspond to the value of the field. Depending on the field type, you need to pass different Python types for the values:

  • Text field values are given with Python strings.
  • Float and Integer field values are given using Python floats or integers.
  • Boolean field values are given preferably using Python Booleans or integers.
  • Date field values are given with the Python datetime.date object.
  • Datetime field values are given with the Python datetime.datetime object.
  • Binary field values are passed as a Base64 encoded string. The base64 module from the Python standard library provides methods such as encodebytes(bytestring) to encode a string in Base64.
  • Many2one field values are given with an integer, which has to be the database ID of the related record.
  • One2many and Many2many fields use a special syntax. The value is a list that contains tuples of three elements, as follows:

Tuple

Effect

(0, 0, dict_val)

Creates a new record that will be related to the main record.

(6, 0, id_list)

Creates a relation between the record being created and existing records, whose IDs are in the Python list called id_list.

Caution: When used on a One2many field, this will remove the records from any previous relation.

 

In this recipe, we create the dictionaries for two contacts in the company we want to create, and then we use these dictionaries in the child_ids entry of the dictionary for the company being created by using the (0, 0, dict_val) syntax we explained earlier.

When create() is called in step 5, three records are created:

  • One for the parent book category, which is returned by create
  • Two records for the child book category, which are available in record.child_ids
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset