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

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

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

Sitio web hecho con

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