Skip to content

Commit 98a6393

Browse files
Merge pull request #866 from JarriqTheTechie/features/only
Added only to Model
2 parents 57aa5cf + 427fc9d commit 98a6393

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/masoniteorm/models/Model.py

+17
Original file line numberDiff line numberDiff line change
@@ -810,6 +810,23 @@ def method(*args, **kwargs):
810810

811811
return None
812812

813+
def only(self, attributes: list) -> dict:
814+
if isinstance(attributes, str):
815+
attributes = [attributes]
816+
results: dict[str, Any] = {}
817+
for attribute in attributes:
818+
if " as " in attribute:
819+
attribute, alias = attribute.split(" as ")
820+
alias = alias.strip()
821+
attribute = attribute.strip()
822+
else:
823+
alias = attribute.strip()
824+
attribute = attribute.strip()
825+
826+
results[alias] = self.get_raw_attribute(attribute)
827+
828+
return results
829+
813830
def __setattr__(self, attribute, value):
814831
if hasattr(self, "set_" + attribute + "_attribute"):
815832
method = getattr(self, "set_" + attribute + "_attribute")

tests/models/test_models.py

+9
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,15 @@ def test_force_update_on_model_class(self):
186186
self.assertIn("username", sql)
187187
self.assertIn("name", sql)
188188

189+
def test_only_method(self):
190+
model = ModelTestForced.hydrate(
191+
{"id": 1, "username": "joe", "name": "Joe", "admin": True}
192+
)
193+
194+
195+
self.assertEquals({"username": "joe"}, model.only("username"))
196+
self.assertEquals({"username": "joe"}, model.only(["username"]))
197+
189198
def test_model_update_without_changes_at_all(self):
190199
model = ModelTest.hydrate(
191200
{"id": 1, "username": "joe", "name": "Joe", "admin": True}

0 commit comments

Comments
 (0)