diff --git a/odoo/fields.py b/odoo/fields.py index 854a2f831b2..8b7cbfe71cc 100644 --- a/odoo/fields.py +++ b/odoo/fields.py @@ -836,7 +836,7 @@ class Field(MetaField('DummyField', (object,), {})): def add_not_null(): # flush values before adding NOT NULL constraint model.flush([self.name]) - model.pool.post_constraint(sql.set_not_null, model._cr, model._table, self.name) + model.pool.post_constraint(apply_required, model, self.name) elif not self.required and has_notnull: sql.drop_not_null(model._cr, model._table, self.name) @@ -3702,6 +3702,16 @@ def prefetch_x2many_ids(record, field): return unique(id_ for ids in ids_list for id_ in ids) +def apply_required(model, field_name): + """ Set a NOT NULL constraint on the given field, if necessary. """ + # At the time this function is called, the model's _fields may have been reset, although + # the model's class is still the same. Retrieve the field to see whether the NOT NULL + # constraint still applies + field = model._fields[field_name] + if field.store and field.required: + sql.set_not_null(model.env.cr, model._table, field_name) + + # imported here to avoid dependency cycle issues from .exceptions import AccessError, MissingError, UserError from .models import check_pg_name, BaseModel, NewId, IdType