Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

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

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
functionimportcustomize
4 Respuestas
3097 Vistas
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
Descartar
Avatar
Savya Sachin
Mejor respuesta

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
Descartar
noone
Autor

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
Mejor respuesta

Add all module to depends section in your manifest file

0
Avatar
Descartar
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
Autor Mejor respuesta

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
Descartar
Avatar
Yahoo Baba Innovations Pvt.Ltd
Mejor respuesta

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
Descartar
noone
Autor

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
Autor

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.

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
How to override IMPORT button on tree view using Odoo 12
import customize button odoo12
Avatar
0
may 20
3291
Issue with import and comma in Excel File (odoo 19)
import
Avatar
0
sept 25
234
production of not enough materials for a PO
function
Avatar
Avatar
Avatar
2
sept 25
1111
POS Product Category Community Edition
function
Avatar
Avatar
1
sept 25
1785
Options for collections management addons for museums or private collection
function
Avatar
0
jul 25
1175
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

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