Skip to Content
Menu
This question has been flagged
1 Reply
3649 Views

If have two entities "payment" and "bill". With each payment the user must be able to pay one or more "biils" That is done by adding a One2Many field (of type bill) in the payment model. How can I add a constrain to ensure that a payment should have at least one bill (ensure that the One2Many list is not empty). I have tried this code but it is not working cause the user can create one payment without having to add "bill" to the One2Many Bills attibute.

`class PaymentCenter(models.Model):
    _name = 'center.payment'
    _description = 'Payment'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    
    bill_ids = fields.One2many('center.bill',
                                    "payment_id",
                                    string=" Bills", required=True)

    @api.constrains('bill_ids')
    def _constrains_bill_ids(self):
        if not self.bill_ids or len(self.bill_ids)==0:
            raise ValidationError("You must add at least one bill to the payment")

class BillCenter(models.Model):
    _name = 'center.bill'
    _inherits = {'ir.attachment': 'attachment_id'}

    payment_id = fields.Many2one('center.payment', string="Payment")
`

Avatar
Discard
Best Answer

Hi Ernesto,

Seems your code is correct.

But you can try either @api.one or put self in a for loop.


Regards


Global Creative Concepts Tech Co Ltd.

Avatar
Discard