Skip to content

Commit 43edab0

Browse files
committed
Added multi get capability
1 parent 62f682b commit 43edab0

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

backend/PyMatcha/utils/orm/_model.py

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def delete(self):
210210
self.db.commit()
211211
logging.debug("deleted {} from table {}".format(self.id, self.table_name))
212212
else:
213-
logging.error("{} Not in table {}".format(self.id, self.table_name))
213+
logging.warning("{} Not in table {}".format(self.id, self.table_name))
214214
raise Exception("{} Not in table {}".format(self.id, self.table_name))
215215

216216
@classmethod
@@ -251,6 +251,52 @@ def get(cls, **kwargs):
251251
else:
252252
raise ValueError("Not found")
253253

254+
@classmethod
255+
def get_multi(cls, **kwargs):
256+
"""
257+
Get a model from the database, using multiple keyword argument as a filter.
258+
259+
Class method allows you to use without instanciation eg.
260+
261+
model = Model.get(username="test", email="test@example.org")
262+
263+
Returns a populated user instance on success and raises an error if the row count was 0
264+
265+
"""
266+
267+
keys = []
268+
values = []
269+
for key, value in kwargs.items():
270+
keys.append(key)
271+
values.append(value)
272+
273+
where = ""
274+
length = len(keys)
275+
for index, (key, value) in enumerate(zip(keys, values)):
276+
if index == length - 1:
277+
where = where + f"{key}={value}"
278+
else:
279+
where = where + f"{key}={value} and "
280+
281+
temp = cls()
282+
with temp.db.cursor() as c:
283+
c.execute(
284+
"""
285+
SELECT
286+
{fields}
287+
FROM
288+
{table}
289+
WHERE {where}""".format(
290+
fields=", ".join(temp.fields.keys()), table=cls.table_name, where=where
291+
)
292+
)
293+
294+
data = c.fetchone()
295+
if data:
296+
return cls(data)
297+
else:
298+
raise ValueError("Not found")
299+
254300
@classmethod
255301
def select_all(cls):
256302
logging.debug("Getting all items from table {}".format(cls.table_name))
@@ -263,7 +309,7 @@ def select_all(cls):
263309

264310
@classmethod
265311
def drop_table(cls):
266-
logging.info("Dropping table {}".format(cls.table_name))
312+
logging.warning("Dropping table {}".format(cls.table_name))
267313
with cls.db.cursor() as c:
268314
c.execute("""DROP TABLE {}""".format(cls.table_name))
269315
cls.db.commit()

0 commit comments

Comments
 (0)