Required field doesn't get unique default values when setting it to required later on

Bug #1311579 reported by Hannes (Neobis)
14
This bug affects 3 people
Affects Status Importance Assigned to Milestone
Odoo Server (MOVED TO GITHUB)
New
Undecided
Unassigned

Bug Description

I created a field with a _defaults method. (see code below)
In this method was a uuid4() value.
After a while I decided that this field should become required. So, i added required=1 on the field definition and updated the database.
I expected that every existing record would get a unique UUID.
What I got was the same unique UUID for every record.

After a bit of investigation I found out where this happens:
http://bazaar.launchpad.net/~openerp/openobject-server/7.0/view/head:/openerp/osv/orm.py#L3169

And indeed, the UPDATE SQL just writes 1 default value to all records.

In my case (UUID) this was a problem and something I didn't expect.

In other cases (like datetime.now()) this can be a less important problem.

Just a simple code example below:

# -*- coding: utf-8 -*-
from openerp.osv import fields, orm
from uuid import uuid4

class MyModel(orm.Model):
    _name = 'my.model'
    _columns = {
        'reference': fields.char('Request reference', required=1),
        'state': fields.selection([('draft', 'Draft'), ('sent', 'Sent')], 'state', required=1)
    }

    def _get_default_reference(self, cr, uid, context=None):
        #TODO: use openerp sequences
        return '%s_%s' % (cr.dbname, str(uuid4()))

    _defaults = {
        'reference': _get_default_reference,
        'state': 'draft',
    }

Later I added:
    _sql_constraints = [
        ('unique_reference', 'unique(reference)', 'A record with the same reference already exists.')
    ]

Then i got:

2014-04-23 10:05:38,042 5014 ERROR db openerp.sql_db: bad query: ALTER TABLE "my_model" ADD CONSTRAINT "my_model_unique_name" unique(reference)
Traceback (most recent call last):
  File "/home/hannes/openerp/openobject-server/7.0/openerp/sql_db.py", line 226, in execute
    res = self._obj.execute(query, params)
IntegrityError: could not create unique index "my_model_unique_name"
DETAIL: Key (reference)=(db_d9833065-58df-43c9-b5db-3bb867d9102b) is duplicate

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.