Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/find_or #837

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/masoniteorm/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ class InvalidUrlConfiguration(Exception):

class MultipleRecordsFound(Exception):
pass


class InvalidArgument(Exception):
pass
1 change: 1 addition & 0 deletions src/masoniteorm/models/Model.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ class Model(TimeStampsMixin, ObservesEvents, metaclass=ModelMeta):
"doesnt_exist",
"doesnt_have",
"exists",
"find_or",
"find_or_404",
"find_or_fail",
"first_or_fail",
Expand Down
28 changes: 26 additions & 2 deletions src/masoniteorm/query/QueryBuilder.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import inspect
from copy import deepcopy
from datetime import datetime
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Callable

from ..collection.Collection import Collection
from ..config import load_config
from ..exceptions import (
HTTP404,
ConnectionNotRegistered,
ModelNotFound,
MultipleRecordsFound,
MultipleRecordsFound, InvalidArgument,
)
from ..expressions.expressions import (
AggregateExpression,
Expand Down Expand Up @@ -1789,6 +1789,30 @@ def find(self, record_id):

return self.where(self._model.get_primary_key(), record_id).first()

def find_or(self, record_id: int, callback: Callable, args=None):
"""Finds a row by the primary key ID (Requires a model) or raise a ModelNotFound exception.

Arguments:
record_id {int} -- The ID of the primary key to fetch.
callback {Callable} -- The function to call if no record is found.

Returns:
Model|Callable
"""

if not callable(callback):
raise InvalidArgument("A callback must be callable.")

result = self.find(record_id=record_id)

if not result:
if not args:
return callback()
else:
return callback(*args)

return result

def find_or_fail(self, record_id):
"""Finds a row by the primary key ID (Requires a model) or raise a ModelNotFound exception.

Expand Down