Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

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

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
functionimportcustomize
4 Respostas
3098 Visualizações
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
Cancelar
Avatar
Savya Sachin
Melhor resposta

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
Cancelar
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
Melhor resposta

Add all module to depends section in your manifest file

0
Avatar
Cancelar
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 Melhor resposta

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
Cancelar
Avatar
Yahoo Baba Innovations Pvt.Ltd
Melhor resposta

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
Cancelar
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.

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
How to override IMPORT button on tree view using Odoo 12
import customize button odoo12
Avatar
0
mai. 20
3292
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
jul. 25
1175
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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