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

Odoo JSON Filter and Offset Parameter

Suscribirse

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

Se marcó esta pregunta
jsonpython3jsonrpc
5 Respuestas
11064 Vistas
Avatar
shirsendudas.2011@gmail.com
i am developing a json rpc based attendance system. so fer i got this below code working as planned except one thing, when searching for last attendance entry id i'm getting full list of ids associated with the related user, this is how search function works, but i want only the last entry id, i thing this can be achieve by using FILTER and OFFSET (maybe), which i'm unable include in my code. can anybody look at this python code and guide me. getting the full list is not an option for me, as i will use arduino later, so memory is limited. and i wanna know how to include this parameters.
import json
import random
import urllib.request
import datetime
import sys

CODE = sys.argv[1] HOST = 'localhost' PORT = 8069 DB = 'ezp' USER = 'root' PASS = 'toor' url = "http://%s:%s/jsonrpc" % (HOST, PORT) date_time = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
def call(url, service, method, *args): id = random.randint(0, 1000000000) data = {"jsonrpc": "2.0", "params": {"args": args, "method": method,"service":service,}, "id": id, "method": "call",} req = urllib.request.Request(url=url, data=json.dumps(data).encode(), headers={"Content-Type":"application/json",}) reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8')) if reply.get("error"): raise Exception(reply["error"]) return reply temp = call(url, "common", "login", DB, USER, PASS) uid = temp["result"] print('Login ID: ' + str(uid))
temp = call(url, "object", "execute", DB, uid, PASS, 'hr.employee', 'search', [['barcode', '=', CODE]]) eid = str(temp["result"])[1:-1] if(eid == ''):   print('Employee not exists')   exit()
temp = call(url, "object", "execute", DB, uid, PASS, 'hr.employee', 'read', int(eid), ['name']) for x in temp["result"]: e_name = x['name'] print('Employee Name: ' +str(e_name))
# below rpc list all the attendance ids associated with this user temp = call(url, "object", "execute", DB, uid, PASS, 'hr.attendance', 'search', [['employee_id','=', int(eid)]]) # how can i insart FILTER PARAMETER so thet only the last entry id returns instead of full list?????? attn = temp["result"]
print('All attendances: ' + str(attn))
def fn_check_in(): attn_record = {'employee_id': eid, 'check_in': date_time} result = call(url, "object", "execute", DB, uid, PASS, 'hr.attendance', 'create', attn_record) print('Checked In : ' + str(e_name), ' At: ' + date_time)
def fn_check_out(id): attn_record = {'check_out': date_time} result = call(url, "object", "execute", DB, uid, PASS, 'hr.attendance', 'write', int(id), attn_record) print('Checked Out : ' + str(e_name), ' At: ' + date_time)
def attendance(): if(len(attn) == 0): fn_check_in() else: last_id = attn[0] for i in range(0, len(attn)): if(attn[i] > last_id): last_id = attn[i] print('Last Entry ID: ' + str(last_id)) is_out = call(url, "object", "execute", DB, uid, PASS, 'hr.attendance', 'read', int(last_id), ['check_out']) if('False' in str(is_out)): fn_check_out(last_id) else: fn_check_in() attendance()
0
Avatar
Descartar
shirsendudas.2011@gmail.com
Autor

Mihran Thalhath i tried your solution and got this server error message

Exception: {'code': 200, 'message': 'Odoo Server Error', 'data': {'name': 'builtins.ValueError', 'debug': 'Traceback (most recent call last):\n File "/odoo/odoo-server/odoo/http.py", line 619, in _handle_exception\n return super(JsonRequest, self)._handle_exception(exception)\n File "/odoo/odoo-server/odoo/http.py", line 309, in _handle_exception\n raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])\n File "/odoo/odoo-server/odoo/tools/pycompat.py", line 14, in reraise\n raise value\n File "/odoo/odoo-server/odoo/http.py", line 664, in dispatch\n result = self._call_function(**self.params)\n File "/odoo/odoo-server/odoo/http.py", line 345, in _call_function\n return checked_call(self.db, *args, **kwargs)\n File "/odoo/odoo-server/odoo/service/model.py", line 93, in wrapper\n return f(dbname, *args, **kwargs)\n File "/odoo/odoo-server/odoo/http.py", line 338, in checked_call\n result = self.endpoint(*a, **kw)\n File "/odoo/odoo-server/odoo/http.py", line 909, in __call__\n return self.method(*args, **kw)\n File "/odoo/odoo-server/odoo/http.py", line 510, in response_wrap\n response = f(*args, **kw)\n File "/odoo/odoo-server/odoo/addons/base/controllers/rpc.py", line 71, in jsonrpc\n return dispatch_rpc(service, method, args)\n File "/odoo/odoo-server/odoo/http.py", line 138, in dispatch_rpc\n result = dispatch(method, params)\n File "/odoo/odoo-server/odoo/service/model.py", line 40, in dispatch\n res = fn(db, uid, *params)\n File "/odoo/odoo-server/odoo/service/model.py", line 93, in wrapper\n return f(dbname, *args, **kwargs)\n File "/odoo/odoo-server/odoo/service/model.py", line 175, in execute\n res = execute_cr(cr, uid, obj, method, *args, **kw)\n File "/odoo/odoo-server/odoo/service/model.py", line 164, in execute_cr\n return odoo.api.call_kw(recs, method, args, kw)\n File "/odoo/odoo-server/odoo/api.py", line 391, in call_kw\n result = _call_kw_model(method, model, args, kwargs)\n File "/odoo/odoo-server/odoo/api.py", line 364, in _call_kw_model\n result = method(recs, *args, **kwargs)\n File "/odoo/odoo-server/odoo/models.py", line 4825, in search_read\n result = records.read(fields)\n File "/odoo/odoo-server/odoo/models.py", line 2879, in read\n raise ValueError("Invalid field %r on model %r" % (name, self._name))\nValueError: Invalid field \'order\' on model \'hr.attendance\'\n', 'message': "Invalid field 'order' on model 'hr.attendance'", 'arguments': ["Invalid field 'order' on model 'hr.attendance'"], 'exception_type': 'internal_error'}}

is there any documentation or guide of proper odoo json structure for "read", "search", "edit", "write" all this operation. along with sort limit offset. i tried finding but got only one example of creating 'note'.

Mihran Thalhath

@shirsendudas.2011@gmail.com

You can check the official web services documentation of Odoo for more details. https://www.odoo.com/documentation/12.0/webservices/odoo.html

Avatar
Mihran Thalhath
Mejor respuesta

Hi,


You can try to use the search_read() method to sort the records by check-in or check-out date in descending order and then apply limit as '1' which will only retrieve the last record. I guess the below code fragment should work. Try and revert back    :)


temp = call(url, "object", "execute", DB, uid, PASS, 'hr.attendance', 'search_read', [['employee_id','=', int(eid)]], {'order': 'check_out desc', 'limit': 1})
1
Avatar
Descartar
Avatar
Hilar Andikkadavath
Mejor respuesta

Try to pass an argument for sorting according to id descending and limit to one record. This gives you the last record from db.

{'order': 'id desc', 'limit': 1}
0
Avatar
Descartar
Avatar
shirsendudas.2011@gmail.com
Autor Mejor respuesta

Solved the issue using "execute_kw" instead "execute" 

call(url, "object", "execute_kw", DB, uid, PASS, 'hr.attendance', 'search', [[['employee_id','=', int(eid)]]],{'limit':1,'order': 'id desc'})
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
How to return a simple json instead object JsonRpc? (Odoo11)
json jsonrpc odoo11
Avatar
Avatar
1
sept 20
7263
JSON-RPC - define request parameters like limit or fields Resuelto
json rpc jsonrpc
Avatar
Avatar
Avatar
6
jul 20
13076
Return reponse as standard json
json jsonrpc odoo12
Avatar
1
mar 20
4199
Selecting a specific db for a json request
json request jsonrpc
Avatar
0
mar 17
5350
JSON-RPC dont use context (return datetime gmt and lang per default)
json mobile jsonrpc
Avatar
Avatar
1
jun 16
8466
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