3

I have an unique constraint for my code field. When I click on the 'duplicate' option in the dropdown action I'm getting the validate error. Is there any way to use 'duplicate' even if the field code is unique?

 class sample(models.Model):
    _name = 'sample'

    code=fields.Char('Code',required=True)
    name=fields.Char('Name',required=True)

    _sql_constraints = [
        ('code_uniq', 'unique (code)', 'The code must be unique !')
    ]
forvas
  • 9,801
  • 7
  • 62
  • 158

1 Answers1

4

Yes, it is. You have two ways to do this. When you duplicate a record, copy method is called, and it creates a new record with the values of the original record (it only copies the values of the fields whose argument copy=True -by default is True-). So you can change that argument in the code field declaration, or modify the copy method to avoid the identical replication.

Way 1: modifying the copy argument of the code field

This way would be the easiest one, but it will give you an error if code field is required.

class sample(models.Model):
    _name = 'sample'

    code = fields.Char('Code', required=False, copy=False)
    name = fields.Char('Name', required=True)

    _sql_constraints = [
        ('code_uniq', 'unique (code)', 'The code must be unique !')
    ]

Way 2: modifying the copy method of the model sample

This is the way you're looking for if code must be required.

class sample(models.Model):
    _name = 'sample'

    code = fields.Char('Code', required=True)
    name = fields.Char('Name', required=True)

    _sql_constraints = [
        ('code_uniq', 'unique (code)', 'The code must be unique !')
    ]

    @api.one
    def copy(self, default=None):
        if default is None:
            default = {}
        new_code = (self.code + ' (copy)') if self.code else ''
        default.update({
            'code': new_code,
        })
        new_sample = super(sample, self).copy(default=default)
        return new_sample
forvas
  • 9,801
  • 7
  • 62
  • 158
  • I'm facing this error when i used way 2 @api.returns('self', lambda value: value.id) AttributeError: 'list' object has no attribute 'id' – Varsha Bolli Apr 06 '18 at 05:04
  • 1
    I have tried way 1 ERROR: null value in column "code" violates not-null constraint DETAIL: Failing row contains (42, null, Cold ,1, 2018-04-06 05:07:34.181, 1, 2018-04-06 05:07:34.181) – Varsha Bolli Apr 06 '18 at 05:11
  • @VarshaBolli The error in **Way 1** makes sense, because when you duplicate the record, `code` is not copied to the new record, and it remains null, and as it's required, it gives you an error. It would be OK if `code` wasn't required, I'll specify that in the answer, but **Way 2** works for sure. – forvas Apr 06 '18 at 07:56