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

many2many fields - how to implement

Suscribirse

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

Se marcó esta pregunta
2 Respuestas
51327 Vistas
Avatar
karlos

I have the table: Employees, which contains only the field 'name' and 'login' (it's associated to the table users)

class Employees(osv.osv):
    _name = 'Employees.Employees'
    _columns = {
         'the_name':fields.char('Name:', size = 50),
         'user_id': fields.many2one('res.users', 'User:', select = True),
     }
Employees()

Example:

'John' -> 'John@gmail.com'

'Marilyn' -> 'marilyn@outlook.com'

Then I have the table: Tasks, which contains the fields 'name', 'description', and 'employees_id'. When a task is created it could contain several employees for the same task, that's why I choose the "many2many" because I could select several employees. So, I have tried the following:

class tasks(osv.osv):
    _name = 'tasks.tasks'
    _columns = {
          'the_name':fields.char('Name', size = 50),
          'description':fields.text('Description'),
          'employees_id':fields.many2many('Employees.Employees', 'Employees', '???', 'user_id', 'All Employees')
     }
tasks()

Example:

'Carry sand' -> 'Carry the whole sand from the beach' -> 'john@gmail.com; marilyn@outlook.com'

'Play' -> 'Play with legos' -> 'john@gmail.com'

But I don't know what to put on "???"..thanks.

0
Avatar
Descartar
Avatar
Simplify it!
Mejor respuesta

You have to do this:

'employees_ids': fields.many2many('Employees.Employees', 'tasks_employees_rel', 'task_id', 'employee_id', 'Employees assigned to task')

To give you a better example.

A employee can be assigned to many tasks

A task can be assigned to many employees

So you have a many2many relation, so that means that you have to create a new table containing both keys.

That what you do with this. You say that you are having a many2many relation with employees so you have to write the first arg the other object name.

Then you have to write which table is going to contain the foreign keys, so you write some descriptive table.

Then you need to give a name to your first key, since you are calling it from tasks you have to write tasks_id.

And then you need to give a name to the other object key.

Finally you have to give the field a name, and that's all.

3
Avatar
Descartar
karlos
Autor

I'm editing my answer..

Avatar
karlos
Autor Mejor respuesta

@Grover Menacho, I was quite sure I needed to create a third table, thanks for warning me that, but here's my doubts.

1) Should I create the third table by code dynamically (if so, how?) or I can go to "pgAdmin III" (postgreSQL management) and create by hand? I think the best approach is dynamically, but I don't know how to create it dynamically to execute in the load of the module.

2) So, with the third table I should have something like this:

  class Employees(osv.osv):
                    _name = 'Employees.Employees'
                    _columns = {
                         'the_name':fields.char('Name:', size = 50),
                         'user_id': fields.many2one('res.users', 'User:', select = True),
                     }
                Employees()

-> Table 'Employees' -> fields: the_name, user_id

class tasks(osv.osv):
    _name = 'tasks.tasks'
    _columns = {
          'the_name':fields.char('Name', size = 50),
          'description':fields.text('Description'),
          'employees_id':fields.many2many('Employees.Employees', 'tasks_employees_rel',  'employee_id', 'task_id', 'All Employees')
    } tasks()

-> table 'Tasks' -> fields: the_name, description (I think employees_id isn't created in the database..Am I wrong??)

And then I need to have a third table, called: tasks_employees_rel, which contains: id, employee_id, task_id...?

0
Avatar
Descartar
karlos
Autor

I've tried this, and I think it worked..because in the database, table 'tasks_employees_rel', the data is being insert. However, I want to make a rule for this. The user A can only view the tasks assigned to his own profile employee. Remember that, whenever I create a employee I assign them a user.

I was trying something like: [('tasks_employees_rel.employee_id, '=', user.id)], without success.

karlos
Autor

I think I'd just solved this too. I will post my resolution later if I'm 100% sure about it. Thanks.

karlos
Autor

The resolution above worked.

¿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