Tessnim
Tessnim

Reputation: 453

Automatically create one2many fields

I hope I'll be clear enough to explain my problem. In account module we have account.payment.term and account.payment.term.line model that are related with one2many relation:

class AccountPaymentTerm(models.Model):
    _name = "account.payment.term"
    _description = "Payment Term"

    line_ids = fields.One2many('account.payment.term.line', 'payment_id', string='Terms', copy=True, default=_default_line_ids)
    period = fields.Selection([('month', '1 Month'),], string='Period', required=True, default='month', help="Select here the period between payments")
    how_much = fields.Float()
    fixed_amount = fields.Float()

class AccountPaymentTermLine(models.Model):
    _name = "account.payment.term.line"
    _description = "Payment Term Line"

    payment_id = fields.Many2one('account.payment.term', string='Payment Terms', required=True, index=True, ondelete='cascade')

I want to create a method in account.payment.term that creates automatically the payment term lines. This method should determine the number of slices number_of_slices = (self.how_much/self.fixed_amount) which will be the number of payment term lines. I tried this code for now:

@api.onchange('fixed_amount')
def automate_creation(self):
    terms = self.line_ids.browse([])
    self.number_of_slices = (self.how_much/self.fixed_amount)
    i = 0
    while i<10:
        terms+=terms.new({'value': 'fixed',
                          'value_amount':100,
                          'days':30,
                          'option':'day_after_invoice_date',
                          'payment_id':self._origin.id})
        i=i+1

This method doesn't seem to work. I don't get my lines in account.payment.term.line.

Upvotes: 0

Views: 238

Answers (2)

Tessnim
Tessnim

Reputation: 453

This code solved my problem, I used new instead of create

@api.onchange('fixed_amount')
def automate_creation(self):
    terms = self.line_ids.browse([])
    self.number_of_slices = (self.how_much/self.fixed_amount)
    days = 30
    i = 0
    while i<self.number_of_slices:
        terms+=terms.new({'value': 'fixed',
                          'value_amount':self.fixed_amount,
                          'days':days,
                          'option':'day_after_invoice_date',
                          'payment_id':self._origin.id})
    self.line_ids = terms

Upvotes: 0

leppy
leppy

Reputation: 99

Try this

@api.onchange('fixed_amount')
def automate_creation(self):
    self.number_of_slices = (self.how_much/self.fixed_amount)
    i = 0
    while i<10:
        term = self.line_ids.create({'value': 'fixed',
                                     'value_amount':100,
                                     'days':30,
                                     'option':'day_after_invoice_date',
                                     'payment_id':self._origin.id})
        self.line_ids |= term
        i=i+1

Upvotes: 1

Related Questions