domain openerp how to compare 2 date fields in odoo

5.6k Views Asked by At

I create a method when I change a date I received a product and qty to the date of stock.move, I declare start_date = fields.Datetime() in my class

def onchange_project(self, cr, uid,start_date):
    """
    onchange handler of start date.
    """  
    pool_stockmove =self.pool.get('stock.move')
    domain =[('date','>=',start_date)]  
    ids = pool_stockmove.search(cr, uid, domain)

it works fine this method but I want to compare "date of stock" between the start_date date >= start_date AND date <= start_date. I want also to format the date like the method on hr_timesheet

cr.execute('SELECT id \
                FROM hr_timesheet_sheet_sheet \
                WHERE (date_from <= %s and %s <= date_to) \
                    AND user_id=%s \
                    AND id <> %s',(sheet.date_to, sheet.date_from, new_user_id, sheet.id))
            if cr.fetchall():
                return False

Thanks

3

There are 3 best solutions below

1
On

You May try something like this

 cr.execute("SELECT id FROM hr_timesheet_sheet_sheet WHERE (date_from >= %s AND date_to <= %s) AND (user_id=%s) AND (id <> %s)",(sheet.date_from,sheet.date_to, new_user_id, sheet.id))                 
 if cr.fetchall():
     return False

I hope this should helpful for you :)

0
On

Dates are stored in string format. You can compare using sql like in your hr example, but I would suggest compare it using ORM, not raw sql. It is more convenient and it is recommended to always use it, because sql escapes security and other checks that is written in code (but maybe it is not the case in your code).

It's hard to understand which date with which you want to compare and why you can't do it.

I guess you want to do something like this:

[('date', '>=', 'start_date'), ('date', '<=', 'start_date')]

Domain is defined as list of tuples. Such syntax means and is used between tuples on default. You can specify it like this (but it is the same thing):

['&', ('date', '>=', 'start_date'), ('date', '<=', 'start_date')]

It means the same thing as above line (if used '|', means or).

Odoo damains use polish notation: https://en.wikipedia.org/wiki/Polish_notation

And for dates formating, you can use python module datetime to change formatting of date if you need to.

0
On

this is a simple ex: employees = self.env['hr.employee'].search([], order='name asc')

    for employee in employees:
        presence_count = self.env['hr.attendance'].search_count([
            ('employee_id', '=', employee.id),
            ('check_in', '>=', date_start_obj.strftime(DATETIME_FORMAT)),
            ('check_out', '<=', date_end_obj.strftime(DATETIME_FORMAT)),
        ])

        absence_count = date_diff - presence_count

        docs.append({
            'employee': employee.name,
            'presence': presence_count,
            'absence': absence_count,
        })