-1

I have a table in the sqlite with column "telegram_id" I want to get all unique records of this column

def get_all_telegram_ids():
    '''Returns all telegram_id from DB'''
    #rows = cursor.execute("SELECT DISTINCT telegram_id FROM locations").fetchall()
    rows = Locations.select(Locations.telegram_id).distinct()
    print(rows)
    return rows

but this code does not work :-(

funnydman
  • 9,083
  • 4
  • 40
  • 55

2 Answers2

0

Seems to be working fine:

import random
from peewee import *

db = SqliteDatabase(':memory:')

class Location(Model):
    telegram_id = IntegerField()
    class Meta:
        database = db

db.create_tables([Location])

for i in range(100):
    Location.create(telegram_id=random.randint(1, 10))

q = Location.select(Location.telegram_id).distinct()
for l in q:
    print(l.telegram_id)

Prints 1-10 with some variation and no duplicates.

Alternative invocation that also works:

q = Location.select(fn.DISTINCT(Location.telegram_id))
for l in q:
    print(l.telegram_id)
coleifer
  • 24,887
  • 6
  • 60
  • 75
-1

but this code does not work :-(

Have you considered reading the documentation

By specifying a single value of True the query will use a simple SELECT DISTINCT. Specifying one or more columns will result in a SELECT DISTINCT ON.

So it doesn't seem like you can just call distinct() with no parameters, it's always at least select(True).

Also when asking questions about things not working, it's usually a good idea to explain the ways in which it is not working e.g. the error you get if there is one, or your expectations versus what you're observing.

Even more so when you don't come close to providing a minimal reproducible example.

Masklinn
  • 34,759
  • 3
  • 38
  • 57