Peewee how select every n+ row?

290 Views Asked by At

Hy! How can I select every second or sixtieth row with peewee? For example (1st, 31st, 61st, 91st, ...) I try with loop but it's very disgusting. Every loop I increase the offset.

I try the peewee.expression but unfortunately notworking:

TypeError: not all arguments converted during string formatting

data = GreDatasDev3.select().order_by(GreDatasDev3.idGreDatasDev.desc()).where(Expression(GreDatasDev3.idGreDatasDev, '%', 60) == 0).limit(168)
deviceDatasList = []
for i in data:
   deviceDatasList.append(
            {
            "idGreDatasDev" : i.idGreDatasDev,
            "time" : str(i.time),
            "panelNumber" : i.panelNumber,
            "battmV" : i.battmV,
            "battmA" : i.battmA,
            "battW" : i.battW,
            "panemV" : i.panemV,
            "panemA" : i.panemA,
            "paneW" : i.paneW,
            "loadmV" : i.loadmV,
            "loadmA" : i.loadmA,
            "loadW" : i.loadW,
            "battStatus" : i.battStatus,
            "paneStatus" : i.paneStatus,
            "loadStatus" : i.loadStatus,
            "percent" : round(100-((13800-i.battmV)/27), 1),
            "windStatus" : i.windStatus,
            "windMax" : i.windMax,
            "windDirection" : i.windDirection,
            "rainFall" : i.rainFall,
            "humidity" : i.humidity,
            "airPressure" : i.airPressure,
            "temperature" : i.temperature
            }
            )

But without .where tag it is working. Just with the last 168 row.

data = GreDatasDev3.select().order_by(GreDatasDev3.idGreDatasDev.desc()).limit(168)
        deviceDatasList = []
        for i in data:
            deviceDatasList.append(
            {
            "idGreDatasDev" : i.idGreDatasDev,
            "time" : str(i.time),
            ...
            }
            )
1

There are 1 best solutions below

2
On

You can use the ROW_NUMBER window function. Details here.

For example:

# Subquery to fetch all users and their rownum (sorted by username)
subq = User.select(
    User,
    fn.ROW_NUMBER().over(order_by=[User.username]).alias('rownum'))

# Get every 6th user:
query = (User
         .select(subq.c.id, subq.c.username)
         .from_(subq)
         .where(Expression(subq.c.rownum, '%', 6) == 0))

for user in query:
    # ...

For this code to work, you need to:

# Manually import Expression to construct the modulo expression,
# since modulo is not supported out-of-the-box in peewee.
from peewee import Expression