2

I have created a choice_student method in which I return an ID in the default of a many2one field related to res.users but I get the error :

AttributeError: 'int' object has no attribute 'get'

This is my code :

student_id = fields.Many2one('res.users', 'Etudiant', readonly=True, required=True, default=lambda self: self.choice_student()  )

@api.onchange('projet_terminer_id')
def choice_student(self):
    return self.env['res.users'].sudo().search([ ('id','=', 45)]).id

2 Answers 2

3

Replace 'onchange' decorator with 'model'

Also field declaration.

Try with following code.

student_id = fields.Many2one('res.users', 'Etudiant', readonly=True, 
                             required=True, default=_default_choice_student)

@api.model
def _default_choice_student(self):
    return self.env['res.users'].sudo().search([('id','=', 45)]).id
Sign up to request clarification or add additional context in comments.

Comments

3

To explain why are you getting this error, let's start step by step:

1- for default value use decorator api.model, and if you have the id don't use search use browse self.env['some.model'].browse(id), but in you case you don't need this at all just do this:

    student_id = fields.Many2one('res.users', 'Etudiant', 
                                readonly=True, required=True, 
                                default=45 )

2- onchange are also a way of setting default value but only on the view, because they are the first thing to be triggered by the client side after loading default values, onchange method are expected to return either None or a dictionary and this is why you are getting and error, AttributeError: 'int' object has no attribute 'get' because the returned value is not None so odoo is trying to get some expected values from the dictionary (like: domain, values) but oops you returned an int not a dictionary and this why Odoo throws this error.

In onchage method just set the value directly on the self record:

    student_id = fields.Many2one('res.users', 'Etudiant', 
                                readonly=True, required=True,
                                default=45) 

    @api.onchange('projet_terminer_id')
    def choice_student(self):
        self.student_id = self.env['res.users'].sudo().browse(45)

From the look of you code I think you can keep the onchange if you want to reset the value of student_id whenever you change projet_terminer_id field.

1 Comment

The return value of his method is int not None, just to clarify.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.