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
    • eLearning
    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 taberna
    • 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
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • 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
    Browse all Industries
  • 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
    • Services for 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

using function in domain filter

Suscribirse

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

Se marcó esta pregunta
functiondomain
4 Respuestas
74978 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.

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