1

I'm using SQLALchemy and Postgresql.

Imagine I have a SQLAlchemy class Items,

There are 100 items in this table, I want to get for example 200 random rows(expected rows are not unique indeed).

for getting less than 100 easily I do:

items = session.query(Items)\
    .order_by(func.random())\
    .limit(80)\
    .all()

But how can I get more than 100 rows if only I have 100?

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59

2 Answers2

1

I'd probably opt to duplicate entries in pure Python rather than SQLAlchemy, basically just looping and randomly picking from your result set, it's not especially elegant but will get the job done:

import random

limit = 200

items = session.query(Items).all()

for i in range(limit):
    print(items[random.randrange(items.count())])
yvesonline
  • 4,609
  • 2
  • 21
  • 32
  • Thanks for your answer. But the point is to implement this using only ORM functionality. – Mehrdad Pedramfar Dec 28 '20 at 14:20
  • 1
    "the point is to implement this using only ORM functionality" - Unless this is a homework assignment where the instructor is insisting on extra arbitrary requirements then don't get too hung up on being an ORM "purist". Just because you are using ORM doesn't necessarily mean that you have to use *only* ORM. – Gord Thompson Dec 28 '20 at 14:39
1

For small-ish tables you could run two selects and select from their union:

q1 = session.query(Items)
q2 = session.query(Items)
cte = q1.union_all(q2).cte()
items_cte = orm.aliased(Items, cte)
items = session.query(items_cte).order_by(func.random())
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153