Search code examples
python-2.7odooodoo-9

Set default values for One2many field


I have a class student_student which have a one2many fieldresult_ids defined like the following:

    result_ids = fields.One2many("schoolresults.detail", "student_id", "School Results", default="_get_subjects")

and

def _get_subjects(self):
     cr = self.pool.cursor()
     self.env
     return self.pool.get('schoolresults.subject').search(cr, self.env.uid, [])

in the other side I have a class schoolresults_subject:

class schoolresults_subject(models.Model):
    _name = "schoolresults.subject"
    _description = "Student's subjects."
    name = fields.Char("Subject")

class schoolresults_detail(models.Model):
    _name = "schoolresults.detail"
    _description = "Student's results."
    student_id = fields.Many2one("student.student", "Student", ondelete="cascade")
    subject_id = fields.Many2one("schoolresults.subject", "Subject")
    result = fields.Float("Result", compute='_compute_value', store=True)

What I'm trying to do is to fill the result_ids with a subjects list from the last class, whenever the user trying to create a new student profile, using the the default parameter in the one2many field. But whenever I try to create a student profile I get this error Wrong values for student.student.result_ids. Please is there anyway to achieve that? enter image description here

PS. I'm using Odoo 9


Solution

  • I could do this by overriding the default_get method:

    def default_get(self, fields):
        res = super(student_student, self).default_get(fields)
        srd = self.env['schoolresults.detail']
        ids=[]
        school_result={'subject_id':1,'result':0} #dict for fields and their values
        sr = srd.create(school_result)
        ids.append(sr.id)
    
    
        res['result_ids'] = ids
        return res
    

    This is how to override default_get for one2many field.

    Credit goes to:Default values for one2many