This question has been flagged
1 Reply
7610 Views

I have a module in which I have to use two fields as identifier (name and date). How can I make a constraint with those two fields? I already have this (note: the function does not work).

 

class clinic_pet(osv.osv):
    def _make_id(self, cr, uid, ids, field_name, arg, context):
        result = {}
        for rec in self.browse(cr, uid, ids, context=context):
            result[rec.id] = rec.name+', '+str(rec.owner_ids)+', '+str(rec.birthdate)
        return result

    _name = 'clinic.pet'
    _columns = {
        'name': fields.char('Name', size=32, required='True', help='Name of the animal'),
        'genre': fields.char('Genre', size=16, help='Genre of the animal'),
        'father': fields.char('Father', size=32, help='Name of the pet s father'),
        'mother': fields.char('Mother', size=32, help='Name of the pet s mother.'),
        'birthdate': fields.date('Birthdate', required='True'),
        'weight': fields.float('Weight', help='Weight of the pet when it was born.'),
        'death': fields.date('Death', help='Date of the pet s death.'),
        'notes': fields.char('Notes', size=256, help='Additional information of the pet.'),
        'contact_info': fields.char('Owner address', size=64, help='Contact information of the pet s owner.'),
        'specie_ids': fields.many2one('clinic.specie', 'Specie', required='True'),
        'owner_ids': fields.many2one('clinic.owner', 'Owner', required='True'),
    'pet_id': fields.function(_make_id, type='char', size=100, string='Pet id'),
    }
    _sql_constraints = [
        ('pet_unique','unique(name,owner_ids,birthdate)','This pet already exists.')
    ]
clinic_pet()

Avatar
Discard
Best Answer

To make your pets unique regarding name, owner and birthdate, your sql_constraint is just fine. (sql_constraints is a list of triples containing: the constraint name, the sql constraint function with arguments (comma seperated list of fields), and the error message)

You wont need your custom pet_id for that purpose.

Note: The sql_constraint is not checked whenever you change a field. It will be checked when you try to write to the database (save button).

 

If you need the pet_id for any other use, please post the detailed error log.

Regards.

Avatar
Discard