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

using function in domain filter

Suscribirse

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

Se marcó esta pregunta
functiondomain
4 Respuestas
74958 Vistas
Avatar
Muszik Adrián

i want to use a function's return as a domain filter.

'product_id' : fields.many2one('product.product', 'products', domain=[('id', 'in',lambda self,cr,uid,ids, context: self._get_technic_warehause(cr,uid,ids,context))])

like that but it sadly wont work.... this is the error i get

2013-12-07 09:59:49,686 16226 ERROR test werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 159, in run_wsgi
    execute(app)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 146, in execute
    application_iter = app(environ, start_response)
  File "/opt/openerp/server/openerp/service/wsgi_server.py", line 417, in application
    return application_unproxied(environ, start_response)
  File "/opt/openerp/server/openerp/service/wsgi_server.py", line 403, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/openerp/web/addons/web/http.py", line 528, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/openerp/web/addons/web/http.py", line 487, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/lib/python2.7/dist-packages/werkzeug/wsgi.py", line 411, in __call__
    return self.app(environ, start_response)
  File "/opt/openerp/web/addons/web/http.py", line 553, in dispatch
    result = handler(request)
  File "/opt/openerp/web/addons/web/http.py", line 618, in <lambda>
    return lambda request: JsonRequest(request).dispatch(method)
  File "/opt/openerp/web/addons/web/http.py", line 251, in dispatch
    body = simplejson.dumps(response)
  File "/usr/share/pyshared/simplejson/__init__.py", line 321, in dumps
    return _default_encoder.encode(obj)
  File "/usr/share/pyshared/simplejson/encoder.py", line 237, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/share/pyshared/simplejson/encoder.py", line 311, in iterencode
    return _iterencode(o, 0)
  File "/usr/share/pyshared/simplejson/encoder.py", line 213, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <function <lambda> at 0x535c230> is not JSON serializable

the function returns a list of Ids, but here is the function itself:

def _get_technic_warehause(self, cr, uid,ids, context=None):
        data = self.browse(cr, uid, ids, context=context)[0]
        pdb.set_trace()
        if data.technic_id.id:
            location_obj = self.pool.get('stock.location')
            lines_ids = location_obj.search(cr, uid, [('user_id', '=', data.technic_id.id)])
            #res = {data['id'] : []}
            res = []
            for line_id in lines_ids:
                prod_info = location_obj._product_get(cr, uid, line_id, context=context)
                for prod_id in prod_info.keys():
                    if prod_info[prod_id] != 0.0:
                        #res[data['id']].append(prod_id)
                        res.append(prod_id)
            return res
        #return {}

is there anyway in openerp to make this work? I know that openerp doesn't allow function fields in domain filter sadly, but anyway to get around it?

1
Avatar
Descartar
Avatar
Henri-Maxime Ducoulombier
Mejor respuesta

Hello there,

I found out how to (very simple) solve this problem. I'm working with Odoo v8 (I don't know if it's working with v7), and all you have to do is to define a function that will return a JSON serializable domain (in fact, a domain as if you had put it directly in your field definition). Here's me code :

class myClass(models.Model)

    ...

    @api.model
    def _getUserGroupId(self):
        return [('groups_id', '=', self.env.ref('module.xml_id').id)]

    rel_ids = fields.Many2many(comodel_name='res.users', relation='my_relation_table_name', column1='rel_id', column2='user_id', string='Relation field', domain=_getUserGroupId)

Hope this helps.

 

5
Avatar
Descartar
Avatar
klacus
Mejor respuesta

Hi.

You can avoid the problem with the new field in python.  This field is must point a fiunction (field.function) and call the function with this. Call the procedure with this function, and the field will be get the result of the function. The doamin will be accept it, you need to hide the new field and you finish with this.

 

 

Sorry for the original hungarian post. :-) +2 pls. :-)

L.

1
Avatar
Descartar
Avatar
Abdul Nazar
Mejor respuesta

Here i am going to give a example of filter employee by his related user.

In Python:

@api.model    def _get_emp_domain(self):
    domain = []    ctx = self.env.context
    if ('user' in self.env.context and 'user' in self.env.context and 'cond' in self.env.context) and ctx.get('val') and ctx.get('cond') and ctx.get('val'):
        domain = [(ctx.get('user'),ctx.get('cond'),ctx.get('val'))]
    return domain


employee_id = fields.Many2one('hr.employee', string="Employee", domain=lambda self:self._get_emp_domain(), required=True,  default=_get_employee)


In XML:

<record id="action_my_custom" model="ir.actions.act_window">

        <field name="name">My List</field>

        <field name="res_model">my.custom</field>

        <field name="view_type">form</field>

        <field name="view_mode">tree,form</field>

        <field name="domain">[('employee_id.user_id','=',uid)]</field>

        <field name="context">{'user': 'user_id','cond': '=','val': uid}</field>

        <field name="view_id" eval="False"/>

        <field name="search_view_id" ref="view_my_custom_filter"/>

    </record>


I hope it will be helpful for you....

 
          

0
Avatar
Descartar
Avatar
bernscheinder
Mejor respuesta

Hi adrian,

Have you solved this bug please, I need something like this!

 

Sincerly,

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
Publicaciones relacionadas Respuestas Vistas Actividad
New api search domain id and condition? Resuelto
function domain api
Avatar
Avatar
1
oct 15
10008
production of not enough materials for a PO
function
Avatar
Avatar
Avatar
2
sept 25
1104
POS Product Category Community Edition
function
Avatar
Avatar
1
sept 25
1773
Options for collections management addons for museums or private collection
function
Avatar
0
jul 25
1168
naked domain set up Resuelto
domain
Avatar
Avatar
Avatar
Avatar
3
jul 25
5921
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