This question has been flagged
4 Replies
10730 Views

I've created my first module (a campsite reservation module) and have everything functioning as I'd like except I haven't been able to figure out how to make a constraint to prevent date overlap on a campsite booking.

I have two models, Campsite and Booking.  I've linked to Sales for customer information.  Booking contains start_date, end_date, site_id, customer_id and duration fields.  When making a new booking, I'd like a constraint that checks to see if the requested campsite is already booked for the requested date range.  I have some basic Python and SQL knowledge but I can't figure out a constraint that checks "incoming" dates against "existing" dates in the database.  I know we're supposed to be concise, but thanks for any help!

Avatar
Discard
Author

Baiju's answer below solved my problem! Thanks very much, Baiju! I don't have enough karma yet to reply to his post. I've been using the Odoo 8 module building tutorial and the constraint syntax is different to what Baiju offered. I'm guessing this is from the Openerp 7 API?

Author

Using your original answer, I managed to get this working using the new API: @api.one @api.constrains('start_date', 'end_date') def _check_date_overlap(self): for date in self: date_ids = self.search([('start_date', '=', date.start_date), ('site_id', '=', date.site_id.id), ('id', '', date.id)]) if date_ids: raise exceptions.ValidationError("Dates overlap, please choose different dates.") Thanks again for your help!

Best Answer

Hi Martin,

You can use this script:-

    _constraints = [
        (_check_date, 'You can not book  same day!', ['start_date','end_date']),
    ]

    def _check_date(self, cr, uid, ids):
        for item in self.browse(cr, uid, ids):
            item_ids = self.search(cr, uid, [('start_date', '<=', item.end_date), ('end_date', '>=', item.start_date),       ('site_id', '=', item.site_id.id), ('id', '<>', item.id)])
            if item_ids:
                return False
        return True

Hope this helps. If any querys please let me know.

Avatar
Discard
Best Answer

https://github.com/odoo/odoo/blob/12.0/addons/account/models/account_fiscal_year.py

def _check_dates(self) givies good example

Avatar
Discard