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
Про цей форум
Допомога

Add required Many2one field pointing to new model defined in the same module

Підписатися

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

Це запитання позначене
modelsv14dependent
1 Відповісти
6698 Переглядів
Аватар
Răzvan Anastasescu

I develop one custom module which contains:

1. one custom model (and it's data defined in XML)

2. one model which extends an existing one by adding a Many2one required field pointing to the custom model above

If I try to configure default value for the required Many2one field it raises constraints errors during installation as by that time the XML data of the dependent model wasn't yet loaded (database already contains values in the existing default model which I extend at point 2, without the new field of course)

The dependent model it's imported first in __init__.py (inside models) but I see it doesn't matter

Of course that by splitting them into two separate modules where I specify the dependency it works, but I'd like to know how can I have them in the same module.

Is there a way to load dependent model XML data before initialising the model which depends on it ?

I've extrapolated a simplified version of what I have

Module structure

my_module
├── __init__.py
├── __manifest__.py
├── data
│   └── my_model_data.xml
└── models
    ├── __init__.py
    ├── extended_model.py
    └── my_model.py

models/my_model.py

# -*- coding: utf-8 -*-
from odoo import models, fields
class MyModel(models.Model):
  _name = 'my_model.category'
  my_field = fields.Char('My Field')


data/my_model_data.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
  <data noupdate="1">
    <record id="my_external_id" model="my_model.category">
      <field name="my_field">weight</field>
    </record>
  </data>
</odoo>

models/extended_model.py

# -*- coding: utf-8 -*-
from odoo import models, fields, api
class ExtendedModel(models.Model):
  _inherit = ['extended.model']
  @api.model
  def _get_default_id(self):
    return self.env.ref('my_module.my_external_id').id
  extended_field = fields.Many2one(
    'my_model.category',
    'Extended field',
    required=True,
    default=_get_default_id
  )


 

0
Аватар
Відмінити
Аватар
Alessandro Fiorino
Найкраща відповідь

You can define the many2one field like this

other_model_id = fields.Many2one(comodel_name = 'model.other', default = lambda self: self._default_other() )

and then add this function

@api.model

def _default_other(self):

    return self.env.ref('other.model.xml_id').id

1
Аватар
Відмінити
Răzvan Anastasescu
Автор

Nope, it is not working either, it's raising no record found (which I've got as well in some of my tests):

`raise ValueError('No record found for unique ID %s. It may have been deleted.' % (xmlid))`

The point is that I don't see in the log any load event of the data.xml with the records of the dependent model before the error is raised

Alessandro Fiorino

Maybe your database already has some records in the extendend.model table ?

If so, Odoo loading the module tries to add the column and set the default value to all the existing rows, before loading the xml data files, and so you get the error.

The simplest way to overcome this is to modify the default method to avoid throwing an error if the xml_id is not found, i.e.

rec=self.env.ref('other.model.xml_id', raise_if_not_found=False)

return rec.id if rec else False

and manually set the default value in the column of existing rows just after installing the module i.e.

self.env['extended.model'].search([]).write({'extendend_field': elf.env.ref('other.model.xml_id').id})

Răzvan Anastasescu
Автор

Yes, my problems were actually 2:

- having already records in the DataBase, and I've used a validation check in the default function

- I had those fields marked as required on model, which was raising error by setting NULL as default value for existing records

So what I did:

- I've moved required form the model to the view

- I've checked in the default function if I have data or not (I was already doing so)

And for the last part, where you mentioned to manually set the default for the existing records after the module is installed:

- I guess you meant to actually run that code manually (using Odoo shell or custom script)

- but I will try to automatically call that from dependent data XML using function, so it will be done automatically after the data will be loaded (I hope it will work, I'll get there later today)

Your initial answer was inspiring in another way, meaning that you gave me the idea to use a lambda filter which actually calls a function (with parameters)

I did use lambda and separate function (without parameters) for fields default and domain, but haven't thought to combine the two in order to be able to use parameters :)

And that's nice as I have in there quite a few fields with couple of separate functions, and now I can build only one function and pass parameters through lambda

Thank you very much for your help !

Răzvan Anastasescu
Автор

For setting default values for existing records a better approach it will be using a post_init_hook actually, instead of view function (which should work as well, but more dirty)

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 Відповіді Переглядів Дія
How do I create an ir.config_parameter record? Вирішено
models v14
Аватар
Аватар
1
лип. 22
11372
How can I link odoo website with backend
models website_builder v14 back-end
Аватар
Аватар
1
серп. 25
4823
Warning on Odoo 14 with track_visibility Вирішено
code models warning v14
Аватар
Аватар
1
жовт. 24
23401
[Odoo 14] - Model is not updating via Controller
widget models controllers v14
Аватар
Аватар
1
вер. 21
5499
Attached PDF file is not formatted properly
v14
Аватар
0
груд. 25
100
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
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