Home > Back-end >  Odoo 13 : create multiple records via create function
Odoo 13 : create multiple records via create function

Time:10-14

This is my first create function I have ever written in Odoo13. I want to get a period between 2 dates begin_date and end_date and the dates should be saved in a list. From this list I want to create records for a single employee for every day in the list. But my code doesn't seem to be correct and I get this kind of error : AttributeError: 'NoneType' object has no attribute 'id'

This is my code :

from datetime import timedelta, datetime, date
from calendar import monthrange


from odoo import api, fields, models, tools
from odoo.exceptions import UserError, AccessError, ValidationError
from odoo.tools import date_utils


class TimeOff(models.Model):
    _name = 'project.timeoff'
    _rec_name = 'employ_id'

    employ_id = fields.Many2one('hr.employee', string='Employee', required='1')

    date = fields.Date('Date', required=True, index=True,
                       default=fields.Date.context_today)

    begin_date = fields.Datetime(
        'First Day of Leave', required='1')

    day_hours = fields.Integer('Off hours per day', default='8', required='1')
    end_date = fields.Datetime(
        'Last Day of Leave')

###### create function #######
    @api.model
    def create(self, vals):
        range_date = []    # empty list
        if self.employ_id: # check if field has value
            if self.begin_date and self.end_date: # check if field has value
                range_date = self.calc_dates(
                    self.begin_date, self.end_date, mode='date') # call custom function and expect a list to be returned
                if range_date is None:
                    raise ValidationError("Something went wrong") # list is empty
                else: # iterate through list and create record for each date 
                    for day in range_date:
                        vals = {
                            'employ_id': self.employ_id,
                            'begin_date': day}
                        return super(TimeOff, self).create(vals)

### custom function to get all dates between begin_date and end_date #####

    def calc_dates(self, date1, date2, mode='date'):
        date_from = fields.Date.from_string(date1)
        date_to = fields.Date.from_string(date2)

        delta = date_to - date_from

        if delta.days < 0: 
            return None

        dates = []

        for n in range(delta.days   1):
            if mode == 'date':  # returns dates as date format
                dates.append(date_from   timedelta(days=n))
            if mode == 'string': # returns dates as string format
                dates.append(fields.Date.to_string(
                    date_from   timedelta(days=n)))
        return dates


So when I press create I get this error :

Error:
Odoo Server Error

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 624, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 310, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/usr/lib/python3/dist-packages/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 669, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 350, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 915, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 515, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1327, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1319, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 385, in call_kw
    result = _call_kw_model_create(method, model, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 366, in _call_kw_model_create
    return result.id if isinstance(args[0], Mapping) else result.ids
AttributeError: 'NoneType' object has no attribute 'id'

Either I can't use self iin this issue or something is wrong with the return

CodePudding user response:

Since self is an empty record set, self.employ_id will be evaluated to False and Odoo will not execute the if statement, then will return the default value None.

You can call super (without returning the result) with a list of vals, but this will change the behavior of the create method, it is supposed to Tree View

  • Related