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
    • e-learning
    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 pub
    • 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
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • 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
    Explorar todos los sectores
  • 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
    • Servicios para 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

Domain, filter date and month

Suscribirse

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

Se marcó esta pregunta
filterdomaindatesalemonth
2 Respuestas
37268 Vistas
Avatar
Youri Lebarch

Hello,
I try to create a filter domain in sale.report as : Month(order_date) = month(current_date) AND Day(order_date) <= Day(current_date).



<filter string="New Filter" domain="[(('date').strftime('%%m'),'=',((context_today()).strftime('%%m'))),
            (('date').strftime('%%d'),'&gt;=', ((context_today()).strftime('%%d')))]"/> 


I have a problem in left side of domain : ('date'), System say: AttributeError: object has no attribute 'strftime'.

try many combination, but response it's same.

Have you an idea ? What is the type of object 'date' ?


Thanks

1
Avatar
Descartar
Avatar
Youri Lebarch
Autor Mejor respuesta

Temur, thanks for your response. 
I try all of that, but always same problem ("AttributeError: object has no attribute 'strftime'."). An other idea ?


<filter string="This 1" domain="[(strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 2" domain="[(time.strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 3" domain="[(date.strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 5" domain="[(datetime.date.strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 6" domain="[(datetime.time.strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 7" domain="[(datetime.datetime.strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 4" domain="[(datetime.strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 5" domain="[(datetime.date().strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 6" domain="[(datetime.time().strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 7" domain="[(datetime.datetime().strptime('date','%%m'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 5" domain="[(datetime.date().strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 6" domain="[(datetime.time().strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 7" domain="[(datetime.datetime().strptime('date','%%Y-%%m-%%d'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 10" domain="[(datetime.date('date'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 11" domain="[(datetime.time('date'),'=', ((context_today()).strftime('%%m')))]"/> <filter string="This 12" domain="[(datetime.datetime('date'),'=', ((context_today()).strftime('%%m')))]"/> filter string="This 11" domain="[(datetime.time('date').strftime('%%m'),'=', ((context_today()).strftime('%%m')))]"/>


EDIT : 

Finally, i found the solution : sale.report is not a real model, it's a view. For add field, you need to overwrite select method. So : 

 class sale_report(osv.osv):
    _inherit = 'sale.report' 
    
    date_order_month = fields.Char(string='Date Month')
    date_order_day = fields.Char(string='Date Day')
    

    def _select(self):
        select_str = """
             SELECT min(l.id) as id,
                    l.product_id as product_id,
                    t.uom_id as product_uom,
                    sum(l.product_uom_qty / u.factor * u2.factor) as product_uom_qty,
                    sum(l.product_uom_qty * l.price_unit * (100.0-l.discount) / 100.0) as price_total,
                    count(*) as nbr,
                    s.date_order as date,
                    date_part('month', s.date_order) as date_order_month,
                    date_part('day', s.date_order) as date_order_day,
                    s.date_confirm as date_confirm,
                    s.partner_id as partner_id,
                    s.user_id as user_id,
                    s.company_id as company_id,
                    extract(epoch from avg(date_trunc('day',s.date_confirm)-date_trunc('day',s.create_date)))/(24*60*60)::decimal(16,2) as delay,
                    s.state,
                    t.categ_id as categ_id,
                    s.pricelist_id as pricelist_id,
                    s.project_id as analytic_account_id,
                    s.section_id as section_id
        """
        return select_str

1
Avatar
Descartar
Temur

I never used any operation in a left part of condition, normally there is only field name in the left part... I'm curious if it's allowed/supported? if it works in general, then you have to strptime a 'date' first with it's original format %Y-%m-%d" and then strftime it to month using "%m" format:

domain = "[ ( datetime.datetime.strptime('date','%%Y-%%m-%%d').strftime('%%m'), '=' , context_today().strftime('%%m') ) ]"
here right side: context_today().strftime('%%m') is ok: in the left side if operations allowed here (other then simple field names) and 'date' will be inserted correctly than this should work. otherwise consider to add computed field, lets say named as 'date_month' and then use 'date_month' field as follows:
domain = "[ ( 'date_month', '=' , context_today().strftime('%%m') ) ]
I'm sure about second option, but if you'll get worked first one LMK about the final sollution...
Temur

most probably you'll be limited to use only field names in the left side of condition... computed field will resolve the problem in such case, as I suggested above

Youri Lebarch
Autor

I think you are reason : left operand cannot be an object, juste a string. So i try your proposition but i can't add field in model sale_report. Fields are visible in UI in models but not in database Have you an idea ? class sale_report(osv.osv): _inherit = 'sale.report' date_month = fields.Char(string='Date Month') date_day = fields.Char(string='Date Day') I have not error message

Temur

Upvote for exploring of view based objects in odoo ;) I've not seen view based models in odoo before, it's a bit advanced approach. I've used view based models beyond odoo, actually it was in my "todo someday" list to find out how to use view based models in odoo orm. I thought they are not used here and I was going to do it myself. Thank you for revealing use case of such objects. I see now that there are also few other view based objects, but most of them are used in different reports, anyway no so wide usage and implementation also leaves something to be desired. I think they should be supported better and it should be possible to create/extend view based models more elegantly, rather than overriding _select and stuff like that.

Avatar
Temur
Mejor respuesta

most probably "date" object in that context is date string already formatted as: "%Y-%m-%d" (like '2015-06-03'). if so, then you can't call strftime on string object and you get above mentioned error.


UPDATE:
try to add computed field date_month:

from openerp import models, fields, api 
from datetime import datetime as dt


class sale_report(models.Model):
_inherit = 'sale.report'

date_month = fields.Char(string='Date Month',compute='_get_date_month',store=True,readonly=True)

@api.one
@api.depends('date')
def _get_date_month(self):
self.date_month = dt.
strptime(self.date,'%Y-%m-%d').strftime('%m')

then in your filter you'll be able to use :

domain = "[ ( 'date_month', '=' , context_today().strftime('%%m') ) ]


1
Avatar
Descartar
Youri Lebarch
Autor

I find the solution, sale.report is not a real model, it's a view. For add field, you need to overwrite select method. So : class sale_report(osv.osv): _inherit = 'sale.report' date_order_month = fields.Char(string='Date Month') date_order_day = fields.Char(string='Date Day') def _select(self): select_str = """ SELECT min(l.id) as id, l.product_id as product_id, t.uom_id as product_uom, sum(l.product_uom_qty / u.factor * u2.factor) as product_uom_qty, sum(l.product_uom_qty * l.price_unit * (100.0-l.discount) / 100.0) as price_total, count(*) as nbr, s.date_order as date, date_part('month', s.date_order) as date_order_month, date_part('day', s.date_order) as date_order_day,

¿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
Filter by date of today with a delay
filter domain date
Avatar
Avatar
Avatar
3
abr 16
41437
Filter many2one field with functional field
filter domain
Avatar
Avatar
Avatar
5
sept 20
13691
In date field, is it possible to display month and year only?
date month
Avatar
1
ene 20
8474
fillter by date
filter date
Avatar
Avatar
1
sept 16
56
filter invoices for this month
filter date
Avatar
0
mar 15
5569
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 empresariales de código abierto que cubre 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