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

Set defaults based on id

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
defaultsodooV8
3 Respostas
8668 Visualizações
Avatar
tudor

Hello,

I am trying to set some default values, but i can't figure it out. I have added a many2one field to the Product model, which i would like to have the default value of default_code (internal reference) which is a char field. In the _defaults i call the _get_default_code function, where i assume i have to first find the current product and get its default code (i don't know how to do this), then create a new product.code with this value, then return this new product.code. This is what i have so far:

class product_code(osv.osv):
_name = 'product.code'
_columns = {
'name': fields.char('Name', required=True, translate=True),
}

class product_legacy(osv.osv):

_inherit = 'product.template'
_columns = {
'default_code': fields.many2one('product.code', 'Internal Reference'),
}

def _get_default_code(self, cr, uid, context=None):
#get current product's default code
#res = self.pool.get('product.template').search(???)


code_obj = self.pool.get('product.code')
code_obj.create(cr, uid, {
'name': res['name']
}, context=context)

return code_obj

_defaults = {
'default_code':_get_default_code,
}

Even if i put a test value instead of "res['name']" it doesn't do anything. When i create a new product or edit an existing product, the many2one field is still empty.

Thank you for the help.

0
Avatar
Cancelar
Prakash

https://www.odoo.com/es_ES/forum/help-1/question/set-default-value-in-object-of-many2one-field-39425

Avatar
tudor
Autor Melhor resposta

Thank you for the answers. I think i didn't do a very good job explaining my problem. I try again. So, i have the Sales module installed with many products already defined. All the products already have set an 'Internal reference' (default_code). This default_code is of type char.

I have created a module that changes this default_code from char to many2one and references my product.code. This product.code is not defined in the view. I only use it to have this many2one.

The problem is that, as I said, I already have many products with 'internal reference' defined. I would like that when I install my new module, all the 'internal references' already defined to become many2one, with their previous value already set.

So I thought that I can achieve this by setting the _defaults to search for the product with the same id, get the 'internal reference', create a new product.code with it, and set it to the new many2one 'internal reference'.

I don't understand how to search for the product with the same id. Also, even if i return a dummy code_obj from my _get_default_code function, it does not work. The new many2one 'internal reference' is still empty.

Maybe I can't do it like this? Maybe I need to do an update on the database or something.


@Prakash i have already read your post, but i can't figure out how to search for the product with the current id. I assume i have to do something like

self.pool.get('product.product').search(cr, uid, [('id','=',???)], context=context) 

But i don't know what value to search for. Also, as i said, event if I don't use the search and put a dummy code_obj, i get nothing.


@Drees Far I want to have the values set when I install the module, not when I change something. As i said, i think i didn't explain it very well the first time, but maybe now it's more clear.


Thank you

0
Avatar
Cancelar
Prakash

Add on_change for product_id field and using browse method get many2one value. if product_id: product_code = product_obj.browse(cr,uid,product_id).product_code.id

Avatar
Rihene
Melhor resposta

 

Hey friend you can add an on_change function when you click on the code_obj the many2one field will get its containing like this:

Python:

def on_change_state_id(self, cr, uid, ids,code_obj, many_2_one_field, context=None):

if code_obj :
       print code_obj
             res = {'value':{'many_2_one_field':code_obj,
                       }
              }
         return res

else:

My_error_Msg = 'Error : Empty Field'

raise osv.except_osv(_("Error!"), _(My_error_Msg))
   

XML:

<field name="code_obj" on_change="on_change_code_id(code_obj, many_2_one_field)"/>

Regards.


0
Avatar
Cancelar
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
[8.0] Is it possible set a default Partner Bank Account when creating a Payment Order
defaults payment_order odooV8
Avatar
0
jun. 16
4905
How do you use _defaults in the new API? Resolvido
api defaults odooV8
Avatar
Avatar
Avatar
2
fev. 16
7972
CONFIGURACION DE CORREO PROPIO POR PRUMERA VEZ
odooV8
Avatar
0
mar. 25
1950
How to remove model if not in the py files anymore
odooV8
Avatar
0
jan. 25
4226
Start odoo server automatically in Ubuntu 14.04 on reboot Resolvido
odooV8
Avatar
Avatar
1
ago. 23
15845
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