Skip to content

Commit d482f57

Browse files
committed
Added a class method to get random entries from db with WHERE clauses
1 parent 10c1067 commit d482f57

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

backend/PyMatcha/utils/orm/_model.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,63 @@ def select_random(cls, count):
398398
for item in data:
399399
yield cls(item)
400400

401+
@classmethod
402+
def select_random_multis(cls, count, **kwargs):
403+
"""
404+
Get models from the database, using multiple keyword argument as a filter.
405+
406+
Class method allows you to use without instanciation eg.
407+
408+
model = Model.get(username="test", email="test@example.org")
409+
410+
Returns list of instances on success and raises an error if the row count was 0
411+
"""
412+
413+
keys = []
414+
values = []
415+
for key, value in kwargs.items():
416+
keys.append(key)
417+
values.append(value)
418+
419+
where = ""
420+
length = len(keys)
421+
for index, (key, value) in enumerate(zip(keys, values)):
422+
if isinstance(value, str):
423+
if index == length - 1:
424+
where = where + f"{key}='{value}'"
425+
else:
426+
where = where + f"{key}='{value}' and "
427+
else:
428+
if index == length - 1:
429+
where = where + f"{key}={value}"
430+
else:
431+
where = where + f"{key}={value} and "
432+
temp = cls()
433+
with temp.db.cursor() as c:
434+
c.execute(
435+
"""
436+
SELECT
437+
{fields}
438+
FROM
439+
{table}
440+
WHERE {where}
441+
ORDER BY RAND()
442+
LIMIT {count}
443+
""".format(
444+
fields=", ".join(temp.fields.keys()), table=cls.table_name, where=where, count=count
445+
)
446+
)
447+
448+
data = c.fetchall()
449+
c.close()
450+
if data:
451+
ret_list = []
452+
for i in data:
453+
ret_list.append(cls(i))
454+
return ret_list
455+
else:
456+
return []
457+
401458
@classmethod
402459
def drop_table(cls):
403460
logging.warning("Dropping table {}".format(cls.table_name))

0 commit comments

Comments
 (0)