Question

I making various search options to filter report before printing it. For example giving it a datetime, it would print only records that go in between that datetime. But if user does not provide date, so search would skip that parameter and filter by other chosen options, etc.

And this search is triggered from a wizard where user enters search options and then presses print button. I can't seem to find a way to properly implement conditional search, when you don't know if user enters some criteria or leaves empty. So I managed to make some work around like this:

    card_id = datas['form']['card_id'][0]        
    if card_id:
        start_filter = (1, '=', 1)
        end_filter = (1, '=', 1)
        if datas['form']['start_date']: 
            start_date = datas['form']['start_date']                
            start_filter = ('date', '>=', start_date)
        if datas['form']['end_date']:
            end_date = datas['form']['end_date']
            end_filter = ('date', '<', end_date)

        message_ids = self.pool.get('mail.message').search(self.cr, self.uid, 
        [('res_id', '=', card_id), ('model','=', 'some.model'),
        start_filter, end_filter], order='write_date') 

So basically what it does, it uses 1 = 1 filter / domain on default, so if user do not choose that criteria, it finds all records because 1 = 1 is always true. And if he chooses that criteria, then before search, if condition is triggered and it overwrites default domain with proper one.

But I find this way not really elegant one, because I need to use many if conditions and give default domain in advance for every criteria / condition. I suppose there should be more elegant better way?

Was it helpful?

Solution

You don't need to use a (1, '=', 1) as a default. If you pass the search function an empty list of search tuples, it will return all records after applying any record rules defined for the model..

This pattern is quite common and apart from structuring your code there isn't a way to tidy it up that I am aware of. You could start with an empty list of search tuples and then just call a bunch of methods that generate each search tuple in turn and append to the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top