11
votes

In my OpenERP installation I have the following field, which wasn't required before, but I changed the required argument to True.

'fiscal_position': fields.many2one(
    'account.fiscal.position',
    'Fiscal Position',
    required=True,
    readonly=True,
    states={'draft':[('readonly',False)]}
    ),

In the debug log I see that the ORM tries to set a not null constraint for that field in the database.

2013-01-04 15:28:56 EET STATEMENT:  ALTER TABLE "account_invoice"
    ALTER COLUMN "fiscal_position" SET NOT NULL

How can I prevent that? My idea is to have the required True flag, only for new records and without having a NOT NULL constraint. In other cases PostgreSQL integrity errors occur:

IntegrityError: null value in column "fiscal_position" violates
    not-null constraint

So, how can I have a required field in the form view, without making the ORM touch the database scheme constraints? Or how can I change the field required dynamically, according to the state of the object?

2

2 Answers

13
votes

To make a field required only in some states, leave it as not required in the Model, and in the form view set the conditions on which the field will be required:

<field
    name="fiscal_position"
    attrs="{'required':[('state','in',['pending','open'])]}"
    />
6
votes

If you write required=True in .py file then ORM will add not null constrain to that field.

There are multiple ways to do your code.

  1. Make required=True in .py file and set default value for that field.
  2. Make required=False and set required=True in view.xml.
  3. Make required=False and set required=True in view.xml for some state of object.

This may help to solve your problem.