0
# Search and Filtering
1
2
Advanced search and filtering capabilities using Django-style query syntax. Supports complex queries across all Exchange item types with efficient server-side filtering.
3
4
## Capabilities
5
6
### Query Objects
7
8
```python { .api }
9
class Q:
10
def __init__(self, **kwargs):
11
"""Create a query object for filtering."""
12
13
def __and__(self, other):
14
"""Combine queries with AND logic."""
15
16
def __or__(self, other):
17
"""Combine queries with OR logic."""
18
19
def __invert__(self):
20
"""Negate the query with NOT logic."""
21
```
22
23
### Filtering Methods
24
25
```python { .api }
26
class QuerySet:
27
def filter(self, *args, **kwargs):
28
"""Filter items by criteria."""
29
30
def exclude(self, *args, **kwargs):
31
"""Exclude items matching criteria."""
32
33
def order_by(self, *fields):
34
"""Order results by specified fields."""
35
36
def reverse(self):
37
"""Reverse the order of results."""
38
39
def distinct(self):
40
"""Return distinct results."""
41
42
def count(self):
43
"""Count matching items."""
44
45
def exists(self):
46
"""Check if any items match."""
47
```
48
49
### Search Operators
50
51
```python { .api }
52
# Field lookups (Django-style)
53
field__exact # Exact match
54
field__iexact # Case-insensitive exact match
55
field__contains # Contains substring
56
field__icontains # Case-insensitive contains
57
field__startswith # Starts with
58
field__istartswith # Case-insensitive starts with
59
field__endswith # Ends with
60
field__iendswith # Case-insensitive ends with
61
field__in # In list of values
62
field__range # Between two values
63
field__gt # Greater than
64
field__gte # Greater than or equal
65
field__lt # Less than
66
field__lte # Less than or equal
67
field__isnull # Is null/empty
68
```
69
70
Usage examples:
71
72
```python
73
from exchangelib import Q
74
75
# Simple filtering
76
recent_emails = account.inbox.filter(
77
datetime_received__gte=EWSDateTime.now() - timedelta(days=7)
78
)
79
80
# Complex queries with Q objects
81
important_from_boss = account.inbox.filter(
82
Q(importance='High') & Q(sender__email_address='boss@company.com')
83
)
84
85
# Multiple conditions
86
project_emails = account.inbox.filter(
87
subject__icontains='project',
88
datetime_received__range=(start_date, end_date),
89
has_attachments=True
90
).order_by('-datetime_received')
91
92
# Exclude spam
93
clean_inbox = account.inbox.exclude(
94
Q(sender__email_address__endswith='spam.com') |
95
Q(subject__icontains='lottery')
96
)
97
98
# Calendar searches
99
meetings_this_week = account.calendar.filter(
100
start__gte=week_start,
101
end__lte=week_end,
102
is_cancelled=False
103
).order_by('start')
104
105
# Contact searches
106
company_contacts = account.contacts.filter(
107
company_name__iexact='Example Corp'
108
).order_by('surname', 'given_name')
109
```