Перейти к содержимому
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
Об этом форуме
Помощь

@api.depends not triggering function

Подписаться

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

Этот вопрос был отмечен
ormapimethodapi.depends
6 Ответы
33956 Представления
Аватар
Clément TheSecond

I created a stored (stored=True) computed field.

When  field related to this one are modified, I want to change the value of the field.

So I used @api.depense, as follow :

 
@api.multi @api.depends('lst_price','price','taxes_id','price_extra_ttc','price_extra') def _product_price_ttc(self):
    for record in self:
        record.price_ttc = round(record.lst_price * ( 1 + record.taxes_id.amount),2)

But when one the field of the 'depends' if modified, my function does not fire.

What is wrong with my code ?

1
Аватар
Отменить
Аватар
Clément TheSecond
Автор Лучший ответ

Finally the solution was : display the api.depends fields on the same page than price_ttc, so when those field are not on the same page that price_ttc, even if I update them, It's not working. 

I'm a bit desapointed : I thought that api.depends was working everywhere at every moment, but nope. All the fields must be in the same view than the modified one :(

4
Аватар
Отменить
Temur

I see... you've used store=True in your computed field?

Clément TheSecond
Автор

Yes sir ... but indeed, with a non-stored field, the displayed value is the good one.

Temur

Yes, I know about buggy behavior of compute field when store=True. In such a case it may display wrong value in certain conditions, but if you do not set store property then it works correctly(with default value: store=False). I agree with you, implementation of computed field leaves something to be desired if computed fields are stored fields as in your case. As by default store=Fasle for computed fields but you set it to True explicitly, it should be better to include field definition in your question... it's easy to skip extra information in question if provided, while it's harder to guess a missing part. One of the solutions for your case may be to remove store=True, if it does not affect anything else. You also found an interesting way to get it worked. cheers

Аватар
Bohdan Lisnenko
Лучший ответ

try @api.onchange

it triggers function when fields are changed in gui before writing to database

1
Аватар
Отменить
Clément TheSecond
Автор

Does api.onchange works when the computed field is not displayed ? Because, I can modify (for exemple) price_extra in a page, but price_ttc is not on this page. So, is it going to change price_ttc anyway ?

Bohdan Lisnenko

Yes, it should work. see http://odoo-new-api-guide-line.readthedocs.org/en/latest/decorator.html#api-onchange

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

your function (that computes a field) will fire when you access the computed field (either when field is displayed in UI somewhere or included in UI as invisible or you access field from code using "my_browserecord.my_field", etc...) and NOT otherwise. There is nothing wrong with your code, just wrong expectation about when it should be fired.

0
Аватар
Отменить
Clément TheSecond
Автор

But when I refresh the page (within access to the computed field), the function does not trigger.

Temur

change one the field of the 'depends' and then refresh a page and function is not fired anyway? htat's your scenario?

Clément TheSecond
Автор

See answer above ... thank you anyway :)

Temur

it is possible that compute function is not fired if there is a valid cache. if you change any field listed in @api.depends, then cache will be invalidated, so after it if you access the field, function will be fired. Lets say we change 10 times one of the fields listed as dependency and after it we access the computed field once. In this scenario, if computed fields will be implemented as you expect, we'll have 11 call of compute function instead of 1 call. Why compute function should be fired unless it's absolutely necessary?

E.R. Spada

I am having the same issue: last_buy = fields.Date(compute='_get_lastbuys', string = 'Last Buy', store = True) last_pay = fields.Date(compute='_get_lastpays', string = 'Last Pay', store = True) @api.one @api.depends('credit') def _get_lastbuys(self): SaleModel = self.env['sale.order'] parser_model = report_sxw.rml_parse(self.env.cr, self.env.uid, self._name, context=self.env.context) orders = SaleModel.search([('partner_id', '=', self.id), ('state', 'in', ('progress', 'done', 'shipping_except', 'manual','invoice_except'))], order="date_order desc", limit=1) print "================== orders ====================", orders if orders: print "=================== DATE ORDER=================================", orders.date_order self.last_buy = orders.date_order return orders.date_order return @api.one @api.depends('credit') def _get_lastpays(self): SaleModel = self.env['account.voucher'] parser_model = report_sxw.rml_parse(self.env.cr, self.env.uid, self._name, context=self.env.context) vouchers = SaleModel.search([('partner_id', '=', self.id), ('state', '=', 'posted')], order="id desc", limit=1) if vouchers: self.last_pay = vouchers.date return vouchers.date return When I load the module or delete the fields, it will run and populate the DB, but never again, if I remove store=True, and remove api.depends, it will populate perfectly. But I need to search on this field, so added api.depends?

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
How to use the browse method to fetch all records, no a list of ids? Решено
orm method
Аватар
Аватар
1
авг. 15
31415
consistent keyError for api.depends
api api.depends
Аватар
Аватар
2
июл. 15
11720
method name´s orm
orm method
Аватар
Аватар
2
мар. 15
4915
[8.0] New API - Using Domains - ValueError: Invalid leaf Решено
api method 8.0
Аватар
Аватар
Аватар
5
июл. 18
23260
ORM Create res.partner error Решено
automated actions orm api
Аватар
Аватар
3
дек. 19
6947
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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