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

Added only to Model #866

Merged
merged 7 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version="2.19.2",
version="2.20.0",
package_dir={"": "src"},
description="The Official Masonite ORM",
long_description=long_description,
Expand Down
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