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 get latest date from a date field

Suscribirse

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

Se marcó esta pregunta
pythonodoo9.0
6 Respuestas
9578 Vistas
Avatar
amina

I want to get the latest date from a date field and show it in a new field of an other view so I used this function and it seems I'm doing something wrong what could it be?here is my code

def _get_latest_intervention(self, cr, uid, ids, latest, args, context=None):
       res = {}
       obj_intervention = self.pool.get('c.intervention'
       )for interv in self.browse(cr, uid, ids, context=context):
           intervention_ids = obj_intervention.search(cr, uid,    [('equipement_id' '=',, intervention_id)], order='date_intv'
           , context=context)if intervention_ids:
               res[intervention_id] = intervention_ids[-1:][0
           ]else False
       return:
               res[intervention_id] = res

to explain more this module is about management of technical centers of vehicul so I want to show the latest date of intervention of those technical centers in their form view in the field "latest" so I have created 3 menu items (centre,equipement,intervention) and I have put this function in the centre class

0
Avatar
Descartar
Lucio

You are looping (for _ in self.browse...) in elements of class intervention? I don't know, I'm just guessing from variable names. Is this method inside the class "Centre" ? What's the field that links togheter "centre" and "intervention"? What does equipement has to do with all this?

amina
Autor

yes this methode is in the class"centre" ,I did this fault I wanted to wright 'centre_id' but I wrote 'equipement_id' so there is no equipements menchened in this function every centre has his equipements and all dates of intervention of equipments either it's a corrective maintenace or a preventive one so I want to add a new field in the centre form view named latest,which shows the latest added date in the intervention form view this classes are related of course with relational fields I will put all code to make it clearer

omar ahmed

see this maybe same idea

https://stackoverflow.com/questions/49748892/get-last-order-date-customer-in-odoo-partner-view

Avatar
amina
Autor Mejor respuesta

I changed somethings in my code so I want to show the date in the intervention_id field, here is my code 

# -*- coding: utf-8 -*-

from openerp import models, fields, api

class centre(models.Model):

_name = 'res.partner'

_inherit = ['res.partner']

def _get_latest_intervention(self, cr, uid, ids, field_name, args, context=None):

res = {}

obj_intervention = self.pool.get('c.intervention')

for interv in self.browse(cr, uid, ids, context=context):

intervention_ids = obj_intervention.search(cr, uid, [('centre_id', '=', intervention_id)], order='date_intv', context=context)

if intervention_ids:

res[intervention_id] = intervention_ids[-1:][0]

else:

res[intervention_id] = False

return res

rs_ctr = fields.Char(string='Réseau')

nb_ligne = fields.Integer(string='Lignes')

n_agr = fields.Integer(string='N° d\'agrèment')

chef = fields.Char(string='Chef centre')

prp = fields.Char(string='Propriétaire')

equipement_id = fields.Many2one('product.template','Equipements',select=True)

intervention_id = fields.Date(compute='_get_latest_intervention', type="Date", string='Derniére intervention')

  

properties1 = fields.One2many('product.template','centre_id','Centres')

centre()

class equipement(models.Model):

_name = 'product.template'

_inherit = ['product.template']

name = fields.Char(string='Nom')

num_ligne = fields.Integer(string='N° ligne')

model_mat = fields.Char(string='Model de materiel')

centre_id = fields.Many2one('res.partner','Centres',select=True)

properties2 = fields.One2many('c.maintenance','equipement_id','Equipements')

equipement()


class maintenance(models.Model):

_name = 'c.maintenance'

_description = 'Maintenance'

STATE_SELECTION = [('c','Corrective'),('p','Préventive')]

type_int = fields.Selection(STATE_SELECTION,'Type d\'intervention')

date_intv = fields.Date(string='Date d\'intervention')

equipement_id = fields.Many2one('product.template','Equipements',select=True)

intervention_id = fields.Many2one('c.intervention','Interventions',select=True)

maintenance()

class intervention(models.Model):

_name = 'c.intervention'

STATE_SELECTION = [('c','Corrective'),('p','Préventive')]

_description = 'Interventions'

_inherits = {'res.partner':'centre_id'}

_inherit = {'c.maintenance'}

name = fields.Char(string='Nom')

type_int = fields.Selection(STATE_SELECTION,'Type d\'intervention')

properties4 = fields.One2many('c.maintenance','intervention_id','Interventions')

centre_id = fields.Many2one('res.partner','Centres',select=True)

intervention()

what could be the right way to make this work please 

0
Avatar
Descartar
Melvin

Is there anyway to record the intervention of a field in another field? like computing the field to store the intervention date of another field?

Avatar
Priyesh Solanki
Mejor respuesta

Hi,

Did you define intervention_id as a function field in another object in which you want to see latest intervention ?

0
Avatar
Descartar
amina
Autor

no I definded field latest as the function field am I doing something wrong?

¿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
function get latest date
python odoo9.0
Avatar
Avatar
1
ene 16
4527
ir_attachment: IOError: [Errno 2] No such file or directory Resuelto
python ir_attachment odoo9.0
Avatar
Avatar
1
ago 21
63345
How to mention all channel user in Discuss using shortcuts?
javascript python odoo9.0
Avatar
Avatar
1
sept 20
5519
how to return value to javascript from python? Resuelto
javascript python odoo9.0
Avatar
Avatar
Avatar
Avatar
3
abr 18
32343
How to get a value from json?
python json odoo9.0
Avatar
0
ene 16
4825
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