add from_data() classmethod to Model

This commit is contained in:
2025-12-02 05:56:49 +03:00
parent 54907db896
commit c3a3ead852

View File

@@ -189,6 +189,13 @@ class Model:
raise AttributeError(f"No column '{key}'")
@classmethod
def from_data(cls, data):
instance = cls(cls.table)
instance._data = dict(data)
return instance
@classmethod
def find(cls, condition):
row = db.QueryBuilder(cls.table)\
@@ -196,9 +203,7 @@ class Model:
.first()
if not row:
return None
instance = cls(cls.table)
instance._data = dict(row)
return instance
return cls.from_data(row)
@classmethod
@@ -207,11 +212,7 @@ class Model:
.where(condition, operator)\
.all()
res = []
for row in rows:
instance = cls(cls.table)
instance._data = dict(row)
res.append(instance)
return res
return [cls.from_data(row) for row in rows]
@classmethod
@@ -223,9 +224,7 @@ class Model:
row = db.insert(cls.table, columns, *values.values())
if row:
instance = cls(cls.table)
instance._data = row
return instance
return cls.from_data(row)
return None
@@ -243,7 +242,8 @@ class Model:
def select(cls, sel = "*"):
qb = db.QueryBuilder(cls.table).select(sel)
result = qb.all()
return result if result else []
# return result if result else []
return [cls.from_data(data) for data in (result if result else [])]
def update(self, data):