How to do it...

We assume that in an earlier version of our module, the date_release field was a character field, where people wrote whatever they saw fit as the date. We now realize that we need this field for comparisons and aggregations, which is why we want to change its type to Date. Odoo does a great job at type conversions, but, in this case, we're on our own, which is why we need to provide instructions as to how to transform a database with the previous version of our module installed on a database where the current version can run:

  1. Bump the version in your __manifest__.py file:
    'version': '12.0.1.0.1', 
  1. Provide the pre-migration code in migrations/12.0.1.0.1/pre-migrate.py:
def migrate(cr, version): 
    cr.execute('ALTER TABLE library_book RENAME COLUMN date_release 
TO date_release_char')
  1. Provide the post-migration code in migrations/12.0.1.0.1/post-migrate.py:
from odoo import fields 
from datetime import date 
 
def migrate(cr, version): 
    cr.execute('SELECT id, date_release_char FROM library_book') 
    for record_id, old_date in cr.fetchall(): 
        # check if the field happens to be set in Odoo's internal 
        # format 
        new_date = None 
        try: 
            new_date = fields.Date.to_date(old_date) 
        except ValueError: 
            if len(old_date) == 4 and old_date.isdigit(): 
                # probably a year 
                new_date = date(int(old_date), 1, 1) 
            else: 
                # try some separators, play with day/month/year 
# order ...
pass if new_date: cr.execute('UPDATE library_book SET date_release=%s',
(new_date,))

Without this code, Odoo would have renamed the old date_release column to date_release_moved and created a new one, because there's no automatic conversion from character fields to date fields. From the point of view of the user, the data in date_release will simply be gone.

..................Content has been hidden....................

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