I created a universal keyboard with pagination in telegram bot. It works on a peewee query object ModelSelect, but I can't save it to redis or other storage, now I save it in memory, and every run the object is erased and the keyboard stops working.
I tried:
from playhouse.shortcuts import model_to_dict, dict_to_model
from peewee import *
db = SqliteDatabase('test.db')
class User(Model):
id: int
name: str = TextField()
class Meta:
database = db
# create User table
User.create_table()
# add new User
User(name = "new_user").save()
# select User with id = 1
item = User.select().where(User.id == 1)
print(f"SQL: {item.sql()}")
# try to convert ModelSelect to dict
_dict = model_to_dict(item)
print(_dict)
# try to convert dict to ModelSelect
_item = dict_to_model(User, _dict)
print(_item)
But got error:
SQL: ('SELECT "t1"."id", "t1"."name" FROM "user" AS "t1" WHERE ("t1"."id" = ?)', [1])
Traceback (most recent call last):
File "C:\testfile.py", line 27, in <module>
_dict = model_to_dict(item)
File "C:\Python310\lib\site-packages\playhouse\shortcuts.py", line 74, in model_to_dict
for field in model._meta.sorted_fields:
AttributeError: 'ModelSelect' object has no attribute '_meta'
This is the wrong idea. Serializing model instances to dicts is perfectly fine, and they can be de-serialized back to model instances. You cannot reasonably expect to serialize a query object, though. The query just represents the SQL and, when executed, contains a reference to a cursor object.
If you want to serialize an object, you would: