Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar 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
  • Proyecto
  • 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

How to populate dropdown from the database?

Suscribirse

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

Se marcó esta pregunta
3 Respuestas
6689 Vistas
Avatar
HateCamel

Hi people,

just started learning python and openerp and I am pretty lousy so far, but I am trying.

My question is how to populate selection field with data from the database?

I have a 2 simple tables one with data of the employee(name, surname, emal, department) and the other called departments which only has department names.

When creating a new employee I would like to select the department from the dropdown populated with the departments from my other table. Pretty basic stuff.

class djelatnik(osv.osv):

    
    _inherit= 'department
    _name = 'employee'

    def _fetch_departments(self, cr, uid, ids, context = None):
        res=[]
        cr.execute('select id , department from departments')
        departments=cr.fetchall()
        for dep in departments:
            res.append((dep.id,dep.department))
        return res
    

    _columns = {
        'name': fields.char('name',size=30, required=True, help='name'),
        'surname': fields.char('surname', size=30, required=True, help='surname'),
     
        'odjel': fields.selection(_fetch_departments ,'Departments')
        
    }   

What am I doing wrong?

0
Avatar
Descartar
Zbik

Ansewer updated. You change code and xml.

Avatar
Zbik
Mejor respuesta

Example classes, tables, and selections, between tables in odoo.

UPDATED: with xml

    class department(osv.osv):
        _name = 'department'

        _columns = {
                 'name': fields.char('Department', size=32, required=True),
        }

    class djelatnik(osv.osv):
        _name = 'employee'

        _columns = {
            'name': fields.char('name',size=30, required=True, help='name'),
            'surname': fields.char('surname', size=30, required=True, help='surname'),
            'odjel': fields.many2one('department' ,'Departments')           
        }   

        <record model="ir.ui.view" id="view_employee_form">
            <field name="name">employee.form</field>
            <field name="model">employee</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="employee">                   
                    <field name="name" select="1"/>
                    <field name="surname" select="2"/>
                    <field name="odjel" select='0'/>
                </form>
            </field>
        </record>
        <record model="ir.ui.view" id="view_employee_tree">
            <field name="name">employee.tree</field>
            <field name="model">employee</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                <tree string="employee">
                    <field name="name"/>
                    <field name="surname"/>
                     <field name="odjel"/>
                </tree>
            </field>
        </record>
        <record model="ir.actions.act_window" id="action_employee">
            <field name="name">employee</field>
            <field name="res_model">employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="context">{"search_default_type_date":0}</field>
        </record>
        <menuitem name="HR/HR" id="menu_employee" action="action_employee"/>
        <menuitem name="employee" id="menu_employee_employee_item" parent="menu_employee" action="action_employee"/>

        <record model="ir.ui.view" id="view_department_form">
            <field name="name">department.form</field>
            <field name="model">department</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="department">                   
                    <field name="name" select="1"/>
                </form>
            </field>
        </record>
        <record model="ir.ui.view" id="view_department_tree">
            <field name="name">department.tree</field>
            <field name="model">department</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                <tree string="odjel">
                    <field name="name"/>
                </tree>
            </field>
        </record>
        <record model="ir.actions.act_window" id="action_department">
            <field name="name">department</field>
            <field name="res_model">department</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
        </record>
        <menuitem name="department" id="menu_department_department_item" parent="menu_employee" action="action_department"/>

 

0
Avatar
Descartar
Avatar
HateCamel
Autor Mejor respuesta

Thanks mate but that way I get department,1 and so on. How do I get to display the name and not the id?

 

I am using v7.

 

<?xml version="1.0"?>
<openerp>
    <data>
        <record model="ir.ui.view" id="view_employee_form">
            <field name="name">employee.form</field>
            <field name="model">employee</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="employee">                   
                    <field name="name" select="1"/>
                    <field name="surname" select="2"/>
                    <field name="department" select='0'/>
                </form>
            </field>
        </record>
        <record model="ir.ui.view" id="view_employee_tree">
            <field name="name">employee.tree</field>
            <field name="model">employee</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                <tree string="employee">
                    <field name="name"/>
                    <field name="surname"/>
                     <field name="department" />
                </tree>
            </field>
        </record>
        <record model="ir.actions.act_window" id="action_djelatnik">
            <field name="name">employee</field>
            <field name="res_model">employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="context">{"search_default_type_date":0}</field>
        </record>
        <menuitem name="HR/HR" id="menu_employee" action="action_employee"/>
        <menuitem name="employee" id="menu_employeek_employee_item" parent="menu_employee" action="action_employee"/>

        <record model="ir.ui.view" id="view_department_form">
            <field name="name">department.form</field>
            <field name="model">departmentl</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="department">                   
                    <field name="department" select="1"/>
                </form>
            </field>
        </record>
        <record model="ir.ui.view" id="view_department_tree">
            <field name="name">department.tree</field>
            <field name="model">department</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                <tree string="odjel">
                    <field name="department"/>
                </tree>
            </field>
        </record>
        <record model="ir.actions.act_window" id="action_department">
            <field name="name">department</field>
            <field name="res_model">department</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
        </record>
        <menuitem name="department" id="menu_department_department_item" parent="menu_department" action="action_odjel"/>
    </data>
</openerp>

 

0
Avatar
Descartar
Zbik

your xml?

Zbik

odoo verison?

Ivan

If you are getting department,1, etc. most probably it is because the department model does not have field that is named 'name'. Or, alternatively you can set the model's _rec_name attribute to a field that you want to display. Or, alternatively you can develop the method name_get() to set the display name.

Avatar
Bole
Mejor respuesta

Heh, the easiest way to achieve that is to make the field many2one instead of selection.. .
If you insist on look and feel of selection field, just add widget="selection" in you xml view definition for that field.. 
 

But somethinng else seems to be the problem.. 
You have a models for employee and for department in odoo already.. 
wich you can modify/extend to your needs.. 

YOur mistake is making the wrong inheritance.. 
model djelatnik should inherit hr_employee, and model odjel should inherit hr_department
your way if mixed sou you get apples and oragnes mixed.. 

hope it helps a bit;)

 

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

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

Inscribirse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información 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 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