On default fill One2many

1.2k views Asked by At

So I'm trying to fill a One2many list by default. I've defined a basic field, read the "special commands" for One2many and Many2many's but it doesn't seem to work for some reason (no error message or whatsoever, just doesn't fill it)

My code:

@api.one
def _get_competitions(self):
    result = []
    values = {'name': 'test', 'xx_price': 550, 'xx_seats_left': 50, 'xx_attending': True}
    result.append((0, 0, values))
    return result

xx_competitions_attendee = fields.One2many('xx.competition.attendee', 'xx_event_id', string="Competitions", default=_get_competitions)

Reworked it a bit and now I'm just returning a search result and still the list doesn't get filled:

@api.model
def _get_competitions(self):
    return self.env['xx.competition.attendee'].search([('xx_event_id.id', '=', self._context.get('active_ids')[0])])

xx_competitions_attendee = fields.One2many('xx.competition.attendee', 'xx_event_id', string="Competitions", default=_get_competitions)

I've already set the Many2one relation in the other model, I didn't think it was of great importance that I should post it here, but to be sure:

class CompetitionAttendee(models.Model):
   _name = 'xx.competition.attendee'

   xx_event_id = fields.Many2one('event.event', string="Event")
1

There are 1 answers

4
Emipro Technologies Pvt. Ltd. On

NOTE :

@api.model
    def _get_competitions(self):
        result = []
        values = {'name': 'test', 'xx_price': 550, 'xx_seats_left': 50, 'xx_attending': True}
        result.append((0, 0, values))
        return result

In above case, you will get values in One2many list because you are passing values to "xx_competitions_attendee" field

@api.model
def _get_competitions(self):
    return self.env['xx.competition.attendee'].search([('xx_event_id.id', '=', self._context.get('active_ids')[0])])

Default method will call when you are going to create record so in context there is not any active_ids so dictionary will return None.

So you may have error : TypeError: 'NoneType' object has no attribute 'getitem'

NOTE:

You just need to set many2one reference while you feel one2many record. Because One2many field is managed by framework it self and it's always being generated against the many2one reference and you have not specify any Many2one reference there.

values = {'many2one_field' : many2one_ref, 'name': 'test', 'xx_price': 550, 'xx_seats_left': 50, 'xx_attending': True,}

You should try following,

@api.model
def _get_competitions(self):
    result = []
    values = {'name': 'test', 'xx_price': 550, 'xx_seats_left': 50, 'xx_attending': True}
    result.append((0, 0, values))
    return result

You have decorated method with wrong decorator, to set default values method must be decorated with @api.model (blank recordset) while @api.one always require recordset to call method.

You may refer Odoo Docs to know more about method decorators.