Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

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

  • CRM
  • e-Commerce
  • Accounting
  • Inventory
  • PoS
  • Project
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

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

Subscribe

Get notified when there's activity on this post

This question has been flagged
modelsv14dependent
1 Reply
6584 Views
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
Discard
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
Discard
Răzvan Anastasescu
Author

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
Author

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
Author

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!

Sign up
Related Posts Replies Views Activity
How do I create an ir.config_parameter record? Solved
models v14
Avatar
Avatar
1
Jul 22
11156
How can I link odoo website with backend
models website_builder v14 back-end
Avatar
Avatar
1
Aug 25
4699
Warning on Odoo 14 with track_visibility Solved
code models warning v14
Avatar
Avatar
1
Oct 24
23276
[Odoo 14] - Model is not updating via Controller
widget models controllers v14
Avatar
Avatar
1
Sep 21
5400
Odoo14 alternative for Automated Translations through Gengo API module
v14
Avatar
Avatar
Avatar
Avatar
3
Sep 25
3570
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة 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 is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

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