Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Нерухомість
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    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
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

Reference field - selection in the context of the current record

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
developmentforms
1 Відповісти
4603 Переглядів
Аватар
Artur Roszczyk

Hey, 


I am implementing simple workflow engine and i have a concept of a workflow and a workflow instance. Workflow can operate on a selected model, therefore the workflow instances of that workflow will contain the reference to an instance of that model.


I am trying to use the reference field to select any model in the database with some constraints.


class eaxpl_workflow(models.Model):

    _name = 'eaxpl.workflow'

    document_model_id = fields.Many2one('ir.model',)

class eaxpl_workflow_instance(models.Model):

    _name = 'eaxpl.workflow_instance'

    workflow_id = fields.Many2one('eaxpl.workflow', string="Workflow", required=True)

    document_model_id = fields.Many2one('ir.model', related='workflow_id.document_model_id')

    document_reference = fields.Reference(selection=?????)



The question is what to put in the place of the question marks to limit the selection of the models to the model loaded to the document_model_id field?


I have found the following snippet but it seems not to have the context of the current record and simply does not work:


    @api.model

    def _reference_models(self):

        models = self.env['ir.model'].sudo().search(

            [('state', '!=', 'manual')])

        return [(model.model, model.name)

                for model in models

                if not model.model.startswith('ir.')]


Also, when used as a selection attribute, the function seems to be called only once, so I see no way of updating this.


How would you approach this?



0
Аватар
Відмінити
Artur Roszczyk
Автор

I have found Many2oneReference type of field:

https://www.odoo.com/documentation/15.0/developer/reference/backend/orm.html#pseudo-relational-fields

This seems to suit my needs, however I can't find an appropriate widget allowing for the selection.

Has anyone implemented such a widget?

Аватар
Cybrosys Techno Solutions Pvt.Ltd
Найкраща відповідь

To limit the selection of the models to the model loaded to the document_model_id field, you can use the following code:

class eaxpl_workflow(models.Model):
    _name = 'eaxpl.workflow'
    document_model_id = fields.Many2one('ir.model',)

class eaxpl_workflow_instance(models.Model):
    _name = 'eaxpl.workflow_instance'
workflow_id = fields.Many2one('eaxpl.workflow', string="Workflow", required=True)
    document_model_id = fields.Many2one(
'ir.model', related='workflow_id.document_model_id')
    document_reference = fields.Reference(
        selection=lambda self: self._reference_models())

    def _reference_models(self):
        if self.document_model_id:
models = self.env['ir.model'].search([('model', '=', self.document_model_id.model)])
 
      else:
models = self.env['ir.model'].search([('state', '!=', 'manual')])
return [(model.model, http://model.name" target="_blank" data-saferedirecturl="model.name)" rel="ugc">https://www.google.com/url?q=http://model.name&source=gmail&ust=1688454077935000&usg=AOvVaw1mvVA_XY05kd8F2DdgS_RC">model.name) for model in models]




Hope it helps

0
Аватар
Відмінити
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
Reference field - selection in context of the current object
development forms
Аватар
Аватар
1
лип. 22
3140
How do I change the name of the module, or rather the name assigned to the module, after I created it in Odoo Studio?
development
Аватар
1
лист. 25
282
Guest House Module - Rental Search Bar
development
Аватар
Аватар
1
лист. 25
154
How to make all branches for user active automatically after login his account?
development
Аватар
Аватар
Аватар
3
лист. 25
374
MrpBom _skip_bom_line skips line of product that has two multi-choice attribute values when both are selected in Apply to variant
development
Аватар
Аватар
1
лист. 25
333
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة 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, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція 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