cundi / blog

push issues as a blog
2 stars 0 forks source link

如何在OpenERP(Odoo)中创建模的字段约束检查?[翻译] #44

Open cundi opened 8 years ago

cundi commented 8 years ago

原文链接:http://odedrabhavesh.blogspot.in/2014/12/how-to-create-constraints-in-openerp.html

How to create constraints in OpenERP?

This will help you to create a constraints in OpenERP.

_constraint is a pre-define field in OpenERP. It is used for adding a constraint on the object.

It takes list of tuple as its argument. The tuple inside the list contains three parameter.

  1. Method (to check the constraint)
  2. The Message (Pop-up message for End User)
  3. List of Fields (fields to apply the constraint)

_constraint will fire if the condition returns False on creation and updation of the record and display the message.

Here is an example of integer data-type. It's fire a constraint if length is not positive.

Here is .py side code:

from openerp.osv import fields, osv
class res_partner(osv.Model):
    _inherit = 'res.partner'

    _columns = {        
        'length': fields.integer('Length', size=64),
    }

    def _check_number(self, cr, uid, ids, context=None):
        for partner in self.browse(cr, uid, ids, context=context):
            if partner.length < 0:
                return False
        return True     

    _constraints = [
        (_check_length, 'Length must be Positive.', ['length'])
    ]

Here is .xml side code:

<?xml version="1.0"?>
<openerp>
    <data>
        <!-- res partner form view-->
        <record id="view_res_partner_extended_form" model="ir.ui.view">
            <field name="name">res.partner.extended.form.view</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form"/>
            <field name="arch" type="xml">
                <field name="email" position="after">
                    <field name="length"/>
                </field>
            </field>
        </record>
    </data>
</openerp>

I hope you like this article. Share your views to improve content. Happy Learning !!!