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 filter records based on groups?

Suscribirse

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

Se marcó esta pregunta
securityfilterdomaingroups
3 Respuestas
27980 Vistas
Avatar
Anas Taji

My goal is to build a domain filter (group rule) to achieve the following scenario:

We have 2 groups G1 & G2, users of G1 can see records created by any member of G1, but not records created by G2 members and vice versa. If user u1 is a member of both G1 & G2, then u1 can see records created by both groups users. Administrator can see all records.

3
Avatar
Descartar
Avatar
Anas Taji
Autor Mejor respuesta

Thanks to Nishant for giving us a good solution. however, this solution is more flexible.

def _groups_id(self, cr, uid, context=None):
    all_groups=self.pool.get('res.groups')
    all_categ =self.pool.get('ir.module.category')
    all_users =self.pool.get('res.users')
    # You need to replace 'Fleet' with your module name. e.g Warehous, Sales ...etc
    c_ids = all_categ.search(cr,uid,[('name','=','Fleet')])
    fleet_g_ids = all_groups.search(cr,uid,[('category_id','in',c_ids)])
    if not fleet_g_ids: return False
    user_group = all_users.browse(cr, uid, uid,context=context).groups_id
    user_group_ids = [ r.id for r in user_group]

    vals = []
    for fg_id in fleet_g_ids:
        if fg_id in user_group_ids:
            vals.append(fg_id)

    if not vals: return False
    return [(6, 0, vals)]


_columns = {
    'groups_id': fields.many2many('res.groups', 'fleet_vehicle_group_rel', 'vid', 'gid', 'Vehicle'),
            }

_defaults = {
    'groups_id': _groups_id,
    }

The domain filter (Groups Rule):

[('groups_id','in',[g.id for g in user.groups_id])]

This will completely solve the scenario, also you don't have to change the source code each time you add/remove a group.

Regards..%

3
Avatar
Descartar
Nishant Kashyap

Well, I will try this solution as soon as possible...But I think that you figured out this approach because of the answer I posted .. And you unvoted it and remove the correct answer sign as well.. Thank you for showing this gratitude.

Anas Taji
Autor

1- I have mentioned you at the beginning of the post.and offered my thanks.

2- I didn't removed my vote, just the best answer sign.(you still have my vote)

3- I gave you two arbitrary votes on some of your answers in return (at the time i did so).

4- This is a better and more flexibile approach for others to follow.

And i still offer my best thanks and regards..%

Nishant Kashyap

Thank you for that , Thankyou.

Samir GUESMI

Getting me an error : Uncaught Error: Expected "]", got "(name)"

Avatar
Nishant Kashyap
Mejor respuesta

Hey Man Dont use the Functional field on the record rules , they wont help you, because record use applies to the record(Direct from the Database) And the functional fields are calculated when the records are shown, so they wont help you in achieveing what you are looking for.Instead try this:

_columns={
     'g1_group':fields.many2one('res.groups', string='G1 Group'),
     'g2_group':fields.many2one('res.groups', string='G2 Group'),
}

def _g1_group(self, cr, uid, context=None):
    all_groups=self.pool.get('res.groups')
    all_users =self.pool.get('res.users')
    g1_ids = all_groups.search(cr,uid,[('name','=','G1 Group')])
    if not g1_ids: return False
    if not g1_ids in all_users.browse(cr, uid, uid,context=context).groups_id:
        return False
    edit_group = all_groups.browse(cr, uid, g1_ids[0],context=context).id
    return edit_group

def _g2_group(self, cr, uid, context=None):
    all_groups=self.pool.get('res.groups')
    all_users =self.pool.get('res.users')
    g2_ids = all_groups.search(cr,uid,[('name','=','G2 Group')])
    if not g2_ids: return False
    if not g2_ids in all_users.browse(cr, uid, uid,context=context).groups_id:
        return False
    edit_group = all_groups.browse(cr, uid, g2_ids[0],context=context).id
    return edit_group

_defaults = {
    'g1_group':lambda self, cr, uid, context:self._g1_group( cr, uid, context=None)
    'g2_group':lambda self, cr, uid, context:self._g2_group( cr, uid, context=None)
}

In the Record rule check Whether the entered user is in the group so that he can see the records.

[('g1_group','in',[g.id for g in user.groups_id])]

to check for the g2 group:

[('g2_group','in',[g.id for g in user.groups_id])]

I hope this may help you.

2
Avatar
Descartar
Anas Taji
Autor

Thanks Nishant, your suggested code solved the problem, but one final thing to discuss before marking the question as solved.

We need to add new field+method+default_value into the source code along with a rule for each new group in the future, as well as no user can be a member for two groups at the same time.

Can we think of a more flexible approach?

Nishant Kashyap

Well, You can add a user in different groups,And a user can be a member of two or more groups at a time, for example lets say g1_group=1 and g2_group=2 so it will check [(1,'in',[1,2,3,45,24])] in record rule.[1,2,3,45,24] is the id of other groups of the user.Well this is the default way, you can check the Setting--->Security---->Record Rules then there "Discussion group" object, there they are doing the same thing.Otherwise: You need to override def fnct_search for the functional field.Due to lack of documentation I did not able to achieve what I was looking for,

Anas Taji
Autor

yes you are right, user can be a member of multiple groups with no problems. however, we still need to write codes each time we decide to add a new group.

I will try to improve the code to gain more flexibility, and post back here.

Thanks again..%

luis

this is exactly what i need, can you put the steps to follow, i mean do i need to create a module with .py file, xml and so.

my goal is to do this on account.invoice, res.partner and product.product . I hope that I make myself clear. thank you for your help.

Avatar
joshuajan
Mejor respuesta

if you set the store=True the domain will filter you data from database. So delete the store=True , you will get the _search_user_ids..!!

0
Avatar
Descartar
Anas Taji
Autor

Thanks for trying to help, but _search_user_ids..!! didn't get called.

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
How can i select only the users belongs to a particular group in a many2many field Resuelto
filter domain users groups may2many
Avatar
Avatar
2
feb 22
8908
Filter many2one field with functional field
filter domain
Avatar
Avatar
Avatar
5
sept 20
13586
Security Fear: Make fields of a model secret without using groups attribute
security groups
Avatar
0
nov 15
5665
Problem with column iteration in domain filter
filter domain
Avatar
1
mar 15
6235
How to allow read parent tasks to followers
filter domain
Avatar
Avatar
Avatar
2
mar 15
8424
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.

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