Skip to content

Commit

Permalink
Added query.count() method to be able to query the number of objects …
Browse files Browse the repository at this point in the history
…matching a filter.
  • Loading branch information
eblis committed Mar 6, 2023
1 parent b1b1272 commit 8b017e0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
4 changes: 3 additions & 1 deletion odata/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _handle_odata_error(self, response):
err.detailed_message = detailed_message
raise err

def execute_get(self, url, params=None):
def execute_get(self, url, params=None, allow_plain_response=False):
headers = {}
headers.update(self.base_headers)

Expand All @@ -112,6 +112,8 @@ def execute_get(self, url, params=None):
if 'application/json' in response_ct:
data = response.json()
return data
elif "text/plain" in response_ct and allow_plain_response:
return response.text
else:
msg = u'Unsupported response Content-Type: {0}'.format(response_ct)
raise ODataError(msg)
Expand Down
16 changes: 13 additions & 3 deletions odata/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def _get_or_create_option(self, name):
def _format_params(self, options):
return '&'.join(['='.join((key, str(value))) for key, value in options.items() if value is not None])

def _new_query(self):
def _new_query(self) -> "Query":
"""
Create copy of this query without mutable values. All query builders
should use this first.
Expand Down Expand Up @@ -176,7 +176,7 @@ def select(self, *values):
option.append(prop.name)
return q

def filter(self, value):
def filter(self, value) -> "Query":
"""
Set ``$filter`` query parameter. Can be called multiple times. Multiple
:py:func:`filter` calls are concatenated with 'and'
Expand All @@ -189,7 +189,7 @@ def filter(self, value):
option.append(value)
return q

def expand(self, *values):
def expand(self, *values) -> "Query":
"""
Set ``$expand`` query parameter
Expand Down Expand Up @@ -293,6 +293,16 @@ def one(self):
raise exc.MultipleResultsFound()
return data[0]

def count(self) -> int:
"""
Return count of objects, matching current filter
Calls current URL + /$count&...params
"""
url = self._get_url() + "/$count"
options = self._get_options()
data = self.connection.execute_get(url, options, allow_plain_response=True)
return int(data)

def get(self, *pk, **composite_keys):
"""
Return a Entity with the given primary key
Expand Down

0 comments on commit 8b017e0

Please sign in to comment.