add from_data() classmethod to Model
This commit is contained in:
24
app/db.py
24
app/db.py
@@ -189,6 +189,13 @@ class Model:
|
|||||||
raise AttributeError(f"No column '{key}'")
|
raise AttributeError(f"No column '{key}'")
|
||||||
|
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_data(cls, data):
|
||||||
|
instance = cls(cls.table)
|
||||||
|
instance._data = dict(data)
|
||||||
|
return instance
|
||||||
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def find(cls, condition):
|
def find(cls, condition):
|
||||||
row = db.QueryBuilder(cls.table)\
|
row = db.QueryBuilder(cls.table)\
|
||||||
@@ -196,9 +203,7 @@ class Model:
|
|||||||
.first()
|
.first()
|
||||||
if not row:
|
if not row:
|
||||||
return None
|
return None
|
||||||
instance = cls(cls.table)
|
return cls.from_data(row)
|
||||||
instance._data = dict(row)
|
|
||||||
return instance
|
|
||||||
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -207,11 +212,7 @@ class Model:
|
|||||||
.where(condition, operator)\
|
.where(condition, operator)\
|
||||||
.all()
|
.all()
|
||||||
res = []
|
res = []
|
||||||
for row in rows:
|
return [cls.from_data(row) for row in rows]
|
||||||
instance = cls(cls.table)
|
|
||||||
instance._data = dict(row)
|
|
||||||
res.append(instance)
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -223,9 +224,7 @@ class Model:
|
|||||||
row = db.insert(cls.table, columns, *values.values())
|
row = db.insert(cls.table, columns, *values.values())
|
||||||
|
|
||||||
if row:
|
if row:
|
||||||
instance = cls(cls.table)
|
return cls.from_data(row)
|
||||||
instance._data = row
|
|
||||||
return instance
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -243,7 +242,8 @@ class Model:
|
|||||||
def select(cls, sel = "*"):
|
def select(cls, sel = "*"):
|
||||||
qb = db.QueryBuilder(cls.table).select(sel)
|
qb = db.QueryBuilder(cls.table).select(sel)
|
||||||
result = qb.all()
|
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):
|
def update(self, data):
|
||||||
|
|||||||
Reference in New Issue
Block a user