Skip to content

Commit

Permalink
Merge pull request #866 from JarriqTheTechie/features/only
Browse files Browse the repository at this point in the history
Added only to Model
  • Loading branch information
josephmancuso authored Jan 4, 2024
2 parents 57aa5cf + 427fc9d commit 98a6393
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/masoniteorm/models/Model.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,23 @@ def method(*args, **kwargs):

return None

def only(self, attributes: list) -> dict:
if isinstance(attributes, str):
attributes = [attributes]
results: dict[str, Any] = {}
for attribute in attributes:
if " as " in attribute:
attribute, alias = attribute.split(" as ")
alias = alias.strip()
attribute = attribute.strip()
else:
alias = attribute.strip()
attribute = attribute.strip()

results[alias] = self.get_raw_attribute(attribute)

return results

def __setattr__(self, attribute, value):
if hasattr(self, "set_" + attribute + "_attribute"):
method = getattr(self, "set_" + attribute + "_attribute")
Expand Down
9 changes: 9 additions & 0 deletions tests/models/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ def test_force_update_on_model_class(self):
self.assertIn("username", sql)
self.assertIn("name", sql)

def test_only_method(self):
model = ModelTestForced.hydrate(
{"id": 1, "username": "joe", "name": "Joe", "admin": True}
)


self.assertEquals({"username": "joe"}, model.only("username"))
self.assertEquals({"username": "joe"}, model.only(["username"]))

def test_model_update_without_changes_at_all(self):
model = ModelTest.hydrate(
{"id": 1, "username": "joe", "name": "Joe", "admin": True}
Expand Down

0 comments on commit 98a6393

Please sign in to comment.