Skip to Content
Odoo Menu
  • Prihlásiť sa
  • Vyskúšajte zadarmo
  • Aplikácie
    Financie
    • Účtovníctvo
    • Fakturácia
    • Výdavky
    • Tabuľka (BI)
    • Dokumenty
    • Podpis
    Predaj
    • CRM
    • Predaj
    • POS Shop
    • POS Restaurant
    • Manažment odberu
    • Požičovňa
    Webstránky
    • Tvorca webstránok
    • eShop
    • Blog
    • Fórum
    • Živý chat
    • eLearning
    Supply Chain
    • Sklad
    • Výroba
    • Správa životného cyklu produktu
    • Nákup
    • Údržba
    • Manažment kvality
    Ľudské zdroje
    • Zamestnanci
    • Nábor zamestnancov
    • Voľné dni
    • Hodnotenia
    • Odporúčania
    • Vozový park
    Marketing
    • Marketing sociálnych sietí
    • Email marketing
    • SMS marketing
    • Eventy
    • Marketingová automatizácia
    • Prieskumy
    Služby
    • Projektové riadenie
    • Pracovné výkazy
    • Práca v teréne
    • Helpdesk
    • Plánovanie
    • Schôdzky
    Produktivita
    • Tímová komunikácia
    • Schvalovania
    • IoT
    • VoIP
    • Znalosti
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Priemyselné odvetvia
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Reštaurácia
    • Fast Food
    • Guest House
    • Beverage distributor
    • Hotel
    Reality
    • Real Estate Agency
    • Architecture Firm
    • Konštrukcia
    • Estate Managament
    • Gardening
    • Property Owner Association
    Poradenstvo
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Výroba
    • Textile
    • Metal
    • Furnitures
    • Jedlo
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware and Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Iní
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Komunita
    Vzdelávanie
    • Tutoriály
    • Dokumentácia
    • Certifikácie
    • Školenie
    • Blog
    • Podcast
    Empower Education
    • Vzdelávací program
    • Scale Up! Business Game
    • Visit Odoo
    Softvér
    • Stiahnuť
    • Porovnanie Community a Enterprise vierzie
    • Releases
    Spolupráca
    • Github
    • Fórum
    • Eventy
    • Preklady
    • Staň sa partnerom
    • Services for Partners
    • Register your Accounting Firm
    Služby
    • Nájdite partnera
    • Nájdite účtovníka
    • Meet an advisor
    • Implementation Services
    • Zákaznícke referencie
    • Podpora
    • Upgrades
    ​Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Získajte demo
  • Cenník
  • Pomoc

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

  • CRM
  • e-Commerce
  • Účtovníctvo
  • Sklady
  • PoS
  • Projektové riadenie
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
Pomoc

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

Odoberať

Get notified when there's activity on this post

This question has been flagged
modelsv14dependent
1 Odpoveď
6701 Zobrazenia
Avatar
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
Avatar
Zrušiť
Avatar
Alessandro Fiorino
Best Answer

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
Avatar
Zrušiť
Răzvan Anastasescu
Autor

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
Autor

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
Autor

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!

Registrácia
Related Posts Replies Zobrazenia Aktivita
How do I create an ir.config_parameter record? Solved
models v14
Avatar
Avatar
1
júl 22
11374
How can I link odoo website with backend
models website_builder v14 back-end
Avatar
Avatar
1
aug 25
4827
Warning on Odoo 14 with track_visibility Solved
code models warning v14
Avatar
Avatar
1
okt 24
23405
[Odoo 14] - Model is not updating via Controller
widget models controllers v14
Avatar
Avatar
1
sep 21
5500
Attached PDF file is not formatted properly
v14
Avatar
0
dec 25
126
Komunita
  • Tutoriály
  • Dokumentácia
  • Fórum
Open Source
  • Stiahnuť
  • Github
  • Runbot
  • Preklady
Služby
  • Odoo.sh hosting
  • Podpora
  • Vyššia verzia
  • Custom Developments
  • Vzdelávanie
  • Nájdite účtovníka
  • Nájdite partnera
  • Staň sa partnerom
O nás
  • Naša spoločnosť
  • Majetok značky
  • Kontaktujte nás
  • Pracovné ponuky
  • Eventy
  • Podcast
  • Blog
  • Zákazníci
  • Právne dokumenty • Súkromie
  • Bezpečnosť
الْعَرَبيّة 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 je sada podnikových aplikácií s otvoreným zdrojovým kódom, ktoré pokrývajú všetky potreby vašej spoločnosti: CRM, e-shop, účtovníctvo, skladové hospodárstvo, miesto predaja, projektový manažment atď.

Odoo prináša vysokú pridanú hodnotu v jednoduchom použití a súčasne plne integrovanými biznis aplikáciami.

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