Skip to content

Commit

Permalink
Add get_list_or_404 shortcut
Browse files Browse the repository at this point in the history
  • Loading branch information
shosca committed May 17, 2018
1 parent 5af6b15 commit 97bbf78
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions django_sorcery/shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,25 @@ def get_object_or_404(klass, *args, **kwargs):
raise Http404("No %s matches the given query." % query)

return instance


def get_list_or_404(klass, *args, **kwargs):
"""
Use filter() to return a list of objects, or raise a Http404 exception if
the count is 0.
klass may be a Model or Query object. All other passed
arguments used in filter() and keyword arguments are used in filter_by().
"""
query = _get_query(klass)

if args:
query = query.filter(*args)

if kwargs:
query = query.filter_by(**kwargs)

if not query.count():
raise Http404("No %s matches the given query." % query)

return query
14 changes: 14 additions & 0 deletions tests/test_shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,17 @@ def test_get_object_or_404(self):

with self.assertRaises(Http404):
shortcuts.get_object_or_404(Owner.query, id=999)

def test_get_list_or_404(self):

obj = shortcuts.get_list_or_404(Owner)
self.assertTrue(list(obj))

with self.assertRaises(Http404):
shortcuts.get_list_or_404(Owner, Owner.first_name.ilike("XXX"))

obj = shortcuts.get_list_or_404(Owner, first_name="Test 1")
self.assertTrue(list(obj))

with self.assertRaises(Http404):
shortcuts.get_list_or_404(Owner, first_name="XXX")

0 comments on commit 97bbf78

Please sign in to comment.