Passa al contenuto
Odoo Menu
  • Accedi
  • Provalo gratis
  • App
    Finanze
    • Contabilità
    • Fatturazione
    • Note spese
    • Fogli di calcolo (BI)
    • Documenti
    • Firma
    Vendite
    • CRM
    • Vendite
    • Punto vendita Negozio
    • Punto vendita Ristorante
    • Abbonamenti
    • Noleggi
    Siti web
    • Configuratore sito web
    • E-commerce
    • Blog
    • Forum
    • Live chat
    • E-learning
    Supply chain
    • Magazzino
    • Produzione
    • PLM
    • Acquisti
    • Manutenzione
    • Qualità
    Risorse umane
    • Dipendenti
    • Assunzioni
    • Ferie
    • Valutazioni
    • Referral dipendenti
    • Parco veicoli
    Marketing
    • Social marketing
    • E-mail marketing
    • SMS marketing
    • Eventi
    • Marketing automation
    • Sondaggi
    Servizi
    • Progetti
    • Fogli ore
    • Assistenza sul campo
    • Helpdesk
    • Pianificazione
    • Appuntamenti
    Produttività
    • Comunicazioni
    • Approvazioni
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    App di terze parti Odoo Studio Piattaforma cloud Odoo
  • Settori
    Retail
    • Libreria
    • Negozio di abbigliamento
    • Negozio di arredamento
    • Alimentari
    • Ferramenta
    • Negozio di giocattoli
    Cibo e ospitalità
    • Bar e pub
    • Ristorante
    • Fast food
    • Pensione
    • Grossista di bevande
    • Hotel
    Agenzia immobiliare
    • Agenzia immobiliare
    • Studio di architettura
    • Edilizia
    • Gestione immobiliare
    • Impresa di giardinaggio
    • Associazione di proprietari immobiliari
    Consulenza
    • Società di contabilità
    • Partner Odoo
    • Agenzia di marketing
    • Studio legale
    • Selezione del personale
    • Audit e certificazione
    Produzione
    • Tessile
    • Metallo
    • Arredamenti
    • Alimentare
    • Birrificio
    • Ditta di regalistica aziendale
    Benessere e sport
    • Club sportivo
    • Negozio di ottica
    • Centro fitness
    • Centro benessere
    • Farmacia
    • Parrucchiere
    Commercio
    • Tuttofare
    • Hardware e assistenza IT
    • Ditta di installazione di pannelli solari
    • Calzolaio
    • Servizi di pulizia
    • Servizi di climatizzazione
    Altro
    • Organizzazione non profit
    • Ente per la tutela ambientale
    • Agenzia di cartellonistica pubblicitaria
    • Studio fotografico
    • Punto noleggio di biciclette
    • Rivenditore di software
    Carica tutti i settori
  • Community
    Apprendimento
    • Tutorial
    • Documentazione
    • Certificazioni 
    • Formazione
    • Blog
    • Podcast
    Potenzia la tua formazione
    • Programma educativo
    • Scale Up! Business Game
    • Visita Odoo
    Ottieni il software
    • Scarica
    • Versioni a confronto
    • Note di versione
    Collabora
    • Github
    • Forum
    • Eventi
    • Traduzioni
    • Diventa nostro partner
    • Servizi per partner
    • Registra la tua società di contabilità
    Ottieni servizi
    • Trova un partner
    • Trova un contabile
    • Incontra un esperto
    • Servizi di implementazione
    • Testimonianze dei clienti
    • Supporto
    • Aggiornamenti
    GitHub Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Richiedi una demo
  • Prezzi
  • Aiuto

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

  • CRM
  • e-Commerce
  • Contabilità
  • Magazzino
  • PoS
  • Progetti
  • MRP
All apps
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
È necessario essere registrati per interagire con la community.
Tutti gli articoli Persone Badge
Etichette (Mostra tutto)
odoo accounting v14 pos v15
Sul forum
Assistenza

Can we import a custom function from one of the custom modules, not from odoo...?

Iscriviti

Ricevi una notifica quando c'è un'attività per questo post

La domanda è stata contrassegnata
functionimportcustomize
4 Risposte
3101 Visualizzazioni
Avatar
noone

Hello guys:


I'm developing in inherit/extension way. 

Some self-made functions are common I want share and reuse in my custom modules, I tried to put them in a module and import them in others,  so I do not need to repeat them everywhere. 

But seems it's not supported ,  an error raised as below:


The directories' structure like this:

Can we import functions from self-made modules?  or we can ONLY import from odoo source directories ?


1
Avatar
Abbandona
Avatar
Savya Sachin
Risposta migliore

Hi, 

You can import Odoo functions from self-made modules and from Odoo source directories. following are a few scenarios with examples.

Importing Odoo Functions in Custom Modules

1. Importing from Odoo source directories

from odoo import models, fields, api

from odoo.exceptions import ValidationError


2. Importing from your own custom modules

# Assuming you have a custom module named 'my_module' with a file 'helpers.py'

from . import helpers

from .models import my_model


3. Relative imports within your module

# In a file within your module, e.g., 'models/product.py'

from . import common

from ..helpers import utils


4. Importing specific functions or classes

from odoo.addons.base.models.res_partner import Partner


5. Using imported functions

class CustomModel(models.Model):

    _name = 'custom.model'


    @api.model

    def custom_method(self):

        #Using a function from Odoo core

        self.env['res.partner'].create({'name': 'New Partner'})

       

        #Using a function from your custom helper

        result = helpers.custom_calculation()

       

        #Using a model from another custom module

        my_model.do_something()


6. Importing and using external libraries

#Make sure the library is installed in your Odoo environment

import requests


def external_api_call(self):

    response = requests.get('https://api.example.com/data')

    # Process the response...


In your case, Try this way to import,

from odoo.addons.my_module1.your_python_file_name import my_method


Note: When importing external libraries, ensure they're listed in your module's external dependencies.

Thanks

1
Avatar
Abbandona
noone
Autore

Hi Savya:

Thanks a lot for your wide-ranging answer! My case is more like the scenario #4, importing across modules but NOT odoo source modules.
Please refer to the lower picture i attached, I defined a method in one of my customized module, and I also need it in other customized modules. So the importing path like ‘ odoo.addons.base... ’ is not applicable.

Yes, i know the solution #5 using "self.env['model_name']. method_name" and it works indeed,
but I'm wondering any chance in 'import' way?

Yahoo Baba Innovations Pvt.Ltd

Hello noone,

You just import below line :
from odoo import fields, models, api

Savya Sachin

I have updated the answer for your case.

Avatar
Alex Dhika
Risposta migliore

Add all module to depends section in your manifest file

0
Avatar
Abbandona
Yahoo Baba Innovations Pvt.Ltd

Hii noone,

Use this line and add you custom logic. This is just an example.

from odoo.addons.account.tools import format_rf_reference

from odoo.addons.account.tools import format_rf_reference

class CustomModule(models.Model):
_name = 'custom.module'

reference_number = fields.Char('Reference Number')
formatted_reference = fields.Char('Formatted Reference', compute='_compute_formatted_reference')

@api.depends('reference_number')
def _compute_formatted_reference(self):
for record in self:
if record.reference_number:
# Use Odoo's format_rf_reference function for formatting
record.formatted_reference = format_rf_reference(record.reference_number)
else:
record.formatted_reference = False

Let me know if you need further clarification!

Avatar
noone
Autore Risposta migliore

I believe most of us must have some functions which are  converged、common and to be used in some other modules. That's what modularity is all about. 

Example #1 :

we know the function 'float_compare()' in base module,  which comparing 2 floats' value.  It's just a function,  not belongs to any model . And it can be used everywhere you need by simply importing it :


Example #2 :

Even in business modules, there also have some shared functions defined in 'tools'  and to be imported in other places. 

In use: 


But similar mechanism does not work in custom modules. I defined a function to compute sequence,  and want to use it in business module (such as employee、partner、products、orders etc.) .  But importing raises error.


Of course I know there're 2 ways :

#1 、 Just repeating the code where I need it ;

#2、 Using "self.env['source_model'].get_sequence " to call it ;

But seems both above are not the reasonable solution,  efficiency or readability is not good. 

I just wondering if and how we can import such custom function from one custom module into another?

0
Avatar
Abbandona
Avatar
Yahoo Baba Innovations Pvt.Ltd
Risposta migliore

Hello noone,

If you are confused please share image what you do or you can connect with me i'll guide where you mistake.

Skype : Yahoo Baba Official

Email:  yahoobaba077@gmail.com

0
Avatar
Abbandona
noone
Autore

Thanks friend ! I've update the image of file structure above.
In short : how to import a custom function from one custom module to another ? Not odoo's function in source / original directories.

Yahoo Baba Innovations Pvt.Ltd

Hii noone,

You need to add this type of function in your local function and add another module name in manifest file in depends.

To add a custom class and use the onchange_custom_function, you can define your custom model class and override the method. Here's the reformatted code including the custom class:

python :
from odoo import models, fields

class CustomModel(models.Model):
_inherit = 'another.module' # Inherit from the appropriate one module.

custom_field = fields.Char('Custom Field')

def onchange_custom_function(self):
rec = super(CustomModel, self).onchange_custom_function()
# Add your custom logic here
return rec
Make sure to include the module's name in the depends section of the manifest file (__manifest__.py), like so:

python copy code:
'depends': ['base_module', 'your_custom_module']

noone
Autore

Thank you very much my friend! Your solution looks like inheriting an exsiting model and override its method.
I meant an indiviual、customized method itself, defined in one custom module and can be utilized in other custom modules.
Let me explain more detail afterwards.

Ti stai godendo la conversazione? Non leggere soltanto, partecipa anche tu!

Crea un account oggi per scoprire funzionalità esclusive ed entrare a far parte della nostra fantastica community!

Registrati
Post correlati Risposte Visualizzazioni Attività
How to override IMPORT button on tree view using Odoo 12
import customize button odoo12
Avatar
0
mag 20
3293
Issue with import and comma in Excel File (odoo 19)
import
Avatar
0
set 25
234
production of not enough materials for a PO
function
Avatar
Avatar
Avatar
2
set 25
1111
POS Product Category Community Edition
function
Avatar
Avatar
1
set 25
1785
Options for collections management addons for museums or private collection
function
Avatar
0
lug 25
1175
Community
  • Tutorial
  • Documentazione
  • Forum
Open source
  • Scarica
  • Github
  • Runbot
  • Traduzioni
Servizi
  • Hosting Odoo.sh
  • Supporto
  • Aggiornamenti
  • Sviluppi personalizzati
  • Formazione
  • Trova un contabile
  • Trova un partner
  • Diventa nostro partner
Chi siamo
  • La nostra azienda
  • Branding
  • Contattaci
  • Lavora con noi
  • Eventi
  • Podcast
  • Blog
  • Clienti
  • Note legali • Privacy
  • Sicurezza
الْعَرَبيّة 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 è un gestionale di applicazioni aziendali open source pensato per coprire tutte le esigenze della tua azienda: CRM, Vendite, E-commerce, Magazzino, Produzione, Fatturazione elettronica, Project Management e molto altro.

Il punto di forza di Odoo è quello di offrire un ecosistema unico di app facili da usare, intuitive e completamente integrate tra loro.

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