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

Create a module that can be inherited to add a common field in other custom modules

Подписаться

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

Этот вопрос был отмечен
inheritanceodoo16features
3 Ответы
5355 Представления
Аватар
ChrisB_USA

I want to add a field to several models which is the date of the weekly accounting period (weekending_date).  Originally I added this field (and a function to set the value) in each model where I required the field.  This resulted in the calculation function being duplicated in several places.

I would like to create a single module that defines the field and the function to calculate it, which I can then inherit in each model where I need it.  That way I only have the function defined once and have consistency across all models.

However, can I do this without it creating a table with just that one field in it?  

When I inherit the module, I want the field to be added into the main model where I need to use the field.  For example

Model account_move should have weekending_date added to it.

Model sale_order should have weekending_date added to it.

Any suggestions for how to do this correctly?



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

Thank you. I think this is correct. I have implemented my first AbstractModel.

Аватар
Mai Chi Trung
Лучший ответ

I believe that is what AbstractModel is used for.

0
Аватар
Отменить
Аватар
Ashish Hirpara
Лучший ответ

To add a field to multiple models and define a calculation function for the field in a single module, you can create a new module and use the _inherit attribute in the module's manifest file to inherit the models that you want to add the field to.

In the new module, you can define the field and the calculation function for the field in the fields.py file. For example, you can create a fields.py file with the following content:

from odoo import fields, models

class WeekendingDate(fields.Date):
    def _compute_weekending_date(self):
        # Code to calculate the weekending date
        pass

In this code, the WeekendingDate class is a subclass of the fields.Date class, and it defines a _compute_weekending_date method that can be used to calculate the weekending date.

Next, in the module's manifest file, you can use the _inherit attribute to inherit the models that you want to add the weekending date field to, and add the weekending date field to the models using the fields.Date class. For example, you can add the following lines to the manifest file:

'_inherit': ['account.move', 'sale.order'],

'fields': {
    'weekending_date': fields.Date('Weekending Date', compute='_compute_weekending_date'),
}

In this code, the _inherit attribute is used to inherit the account.move and sale.order models, and the fields attribute is used to add the weekending_date field to the models. The weekending_date field is defined using the fields.Date class, and it has a compute attribute that specifies the _compute_weekending_date method as the calculation function for the field.

By using the _inherit attribute and the fields attribute in this way, you can add the weekending date field to multiple models in a single module, and define a calculation function for the field that will be used consistently across all the models. This will allow you to avoid duplicating the calculation function in multiple places, and ensure consistency across all the models that have the weekending date field.

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

Thank you very much Ashish. This was helpful. However on attempting to implement it, I was not able to use '_inherit' and 'fields' in the manifest file. That did not work and those properties are not listed in the official documentation for the syntax and properties in the manifest file.

Possibly that was from an earlier version of odoo?

In the end I implemented this as an AbstractModel, which contains the method to calculate the weekending_date. That model is then inherited by each of the models that require the weekending date.

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

Please check the following link for custom module:

https://youtu.be/Xya_fCNr6tw

Thanks & Regards

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
Odoo 16 ce: Inheritance of View to move a field from a group to another
inheritance odoo16features
Аватар
Аватар
Аватар
2
июл. 23
4899
How to conditionally replace field on inherited document and customer preview Решено
inheritance replace odoo16features
Аватар
Аватар
1
мая 23
4116
how to inherit form in odoo 16 Решено
form inheritance odoo16features
Аватар
Аватар
1
мар. 23
4373
DeprecationWarning: The longpolling-port is a deprecated alias to the gevent-port option, please use the latter Решено
odoo16features
Аватар
Аватар
Аватар
Аватар
Аватар
5
сент. 25
24338
How to Add wizard under print button inside the form view.
odoo16features
Аватар
Аватар
Аватар
Аватар
3
авг. 25
3715
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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