Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Заказать демонстрацию
  • Цены
  • Поддержка

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухгалтерия
  • Склад
  • PoS
  • Проекты
  • MRP
All apps
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

"RuntimeError: maximum recursion depth exceeded in cmp" problem

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
one2manyodoo10
4 Ответы
12093 Представления
Аватар
Samo Arko

I've got a weird problem when I call child refresh() method in parent model it works, but if I call it in the child model I get the runtime error.


# Working method in the parent model
@api.multi
def write(self, vals):
record = super(ParentModel, self).write(vals)
for child in self.child_ids:
child.refresh()

# method in child model that throws the error
@api.multi
def write(self, vals):
record = super(ChildModel, self).write(vals)
self.refresh()


The refresh method is calling all the computed methods of the child model and methods that just set data. And I need to call it in the child model when I'm setting data on the child model view and not on the parent model view.

So any ideas how to fix this or why it's happening?

Oh, I've found that this can happen if you have any depends methods, and I call them, but it fails on the every method! I tried commenting them out.

@api.multi
def refresh(self):
for rec in self:
rec._method1()
rec._computed_method1()


0
Аватар
Отменить
Аватар
Jigar Vaghela (jva)
Лучший ответ

don't do refresh under write method. in your compute method decorate with @api.depends(fields name) when this give field name is change then your compute method automatically call.

It's go to a loop because your compute method call write and your write method call compute method..

like 

Write     ⇄    Your compute method.

so remove  refresh() and add depends on your compute method.


Thank you.

1
Аватар
Отменить
Samo Arko
Автор

Thanks for explaining why I get the error. But your tip won't work. The compute methods have already the depends of some fields, but they need data from 2 or 3 different models to correctly calculate values and those 2-3 models depend on a base calculation in the main model. The calculation is done in a editable one2many list so I can't get the values from other models, because the ids of my main model list data are new Objects. That is why I need to refresh the data when I save.

Jigar Vaghela (jva)

so u can add depends like sale.order_line.product_id.price so from your module to other model with many2one, one2many or many2many field. in sort you need relation with other model. if not directly connection then by pass like i do.

sale order to product_price

sale.order_line.product_id.price

so do depends like this

Samo Arko
Автор

thanks, didn't know that you could use depends on relations. will try to use it, but first I have to figure out what should depend on what in the main model and make a plan... a lot of lines of code .

Jigar Vaghela (jva)

Good :+1

Samo Arko
Автор

Nope... it won't work with depends because as soon as a computed field needs a value from child model it fails because of the PoS odoo.models.NewId. I added a button to the view that triggers the refresh method and everything works perfectly. But it's an annoying step for the user! It's really annoying that I can't do this with the save button!

Jigar Vaghela (jva)

you can do it from write but not directly you need to apply some trick.

so first in your ir.actions.act_window pass context like this

<record id="action_parent_model_form" model="ir.actions.act_window">

<field name="name">ParentModel</field>

<field name="type">ir.actions.act_window</field>

<field name="res_model">parent.model</field>

<field name="view_type">form</field>

<field name="view_mode">tree,form</field>

<field name="context">{"update_compute":1}</field>

</record>

now do find this context in write like this

@api.multi

def write(self, vals):

record = super(ParentModel, self).write(vals)

if self._context.get('update_compute'):

for child in self.child_ids:

child.with_context({'update_compute': 0}).refresh()

Samo Arko
Автор

I thing you're a bit off the question. As I said if I call the method from the parent model it works, but calling it from the model where it is defined with write method doesn't work. The method is in the child model of the TOP parent, that child model has his own other child models.

Jigar Vaghela (jva)

then simple same do with child...like this.

@api.multi

def write(self, vals):

record = super(ParentModel, self).write(vals)

if self._context.get('update_compute'):

for child in self.child_ids:

child.with_context({'update_compute': 2}).refresh()

# method in child model that throws the error

@api.multi

def write(self, vals):

record = super(ChildModel, self).write(vals)

if self._context.get('update_compute') == 2:

self.refresh()

Samo Arko
Автор

mate thanks for all your help but this just doesn't want to work. With this it's just the same as without the context. it runs in a infinite loop.

Аватар
Ibrahim Boudmir
Лучший ответ

Hello samo,

"..Maximum recursion depth.."  happens because your function calls the Write (...) function and is declared inside Write (...)!

Moreover, the performance is so poor because you try to loop on self twice!! 

What i suggest is that you pass record and vals to your function refresh() and update vals with the data you need.
It should be like this : 

def write(self, vals):
for record in self:  
record.refresh(record, vals)
return super(YourClass, self).write(vals)
and your refresh would be : 
def refresh(self, record, vals): 
# your cases and update vals each time u want to consider datas changes.  
# For ex: vals['my_field'] = record.field 
# you did not show what your two other functions contain but i think you'll need to pass  
# these arguments too to _method1() function. For the other one, it should be declared outside. Somthing like:  @api.depends('')
def _computed_method1(self):
 for rec in self:  
# your process here
0
Аватар
Отменить
Samo Arko
Автор

thanks for telling me what my code does, but I can't use your suggestion. The data that I refresh are in 2-3 other models and some of the fields in the main model are dependent on the values that are computed in the 2-3 other models. And I'm doing live calc on a one2many list, like a excel table, so I can't change/get data by relations because the list ids are newObjects.

Аватар
BISSTECH SRL
Лучший ответ

Hi Samo,

in your write method, try to call refresh on super, in the same way you do it for write.
Best,
Ioan

super(YourClass, self).refresh()

0
Аватар
Отменить
Samo Arko
Автор

Thanks for trying to help but it doesn't work. It throws an attribute error. AttributeError: 'super' object has no attribute 'refresh'

Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
One2many field odoo version 10
one2many odoo10
Аватар
Аватар
1
сент. 22
2870
Values has false in one2many field when changing the customer in Sale Order ODOO 10
one2many sale.order.line odoo10
Аватар
0
мар. 23
6022
Prevent create and delete on a One2many tree view Решено
treeview one2many odoo10
Аватар
1
июл. 20
9417
Update a field in all One2many lines when a line is added or removed
one2many onchange odoo10
Аватар
0
апр. 20
4966
How to search for records that have child records in One2many relation? Решено
one2many search odoo10
Аватар
Аватар
1
янв. 20
4426
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo – это набор бизнес-модулей с открытым исходным кодом, который закроет все потребности вашей компании: CRM, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

Odoo сочетает в себе простоту использования и полную интеграцию всех бизнес-процессов в одной системе.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now