[英]Sqlalchemy: Accessing a value based on two keys
I'm working on a program using sqlalchemy and want to have one table that stores all the data related to the program.我正在使用 sqlalchemy 开发一个程序,并希望有一个表来存储与该程序相关的所有数据。 Each user of the program has a unique user ID, and one or more items being tracked by the program.
该程序的每个用户都有一个唯一的用户 ID,以及该程序正在跟踪的一个或多个项目。 For each item, there is a single float.
对于每个项目,有一个浮动。 The database layer of the program should, given a user ID and an item name (both strings), provide access to the float or allow for it to be overwritten.
程序的数据库层应该给定一个用户 ID 和一个项目名称(两个字符串),提供对浮点数的访问或允许它被覆盖。
My understanding of the object-relational mapper is that it allows for rows in a table to behave like a storage location for objects on disk memory, but I may be incorrect.我对对象关系映射器的理解是它允许表中的行表现得像磁盘内存上对象的存储位置,但我可能不正确。 I have written the following code, but I'm at a loss for how to retrieve instances, modify them, or create new ones.
我已经编写了以下代码,但我不知道如何检索实例、修改它们或创建新实例。
import datetime
import sqlalchemy as sql
engine = sql.create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Item(Base):
__tablename__ = 'items'
account_id = sql.Column(sql.String, primary_key=True)
name = sql.Column(sql.String, primary_key=True)
timestamp = sql.Column(sql.Float)
def set_now(self):
"""Sets self.timestamp to the Unix timestamp of the present time."""
self.timestamp = datetime.datetime.now().timestamp()
def is_today(self):
"""Returns True if self.timestamp is part of the current day"""
timestamp_dt = datetime.datetime.fromtimestamp(self.timestamp)
return timestamp_dt.date() == datetime.datetime.today().date()
You need to create a sessionmaker
and a session to be able to save or retrieve the records.您需要创建
sessionmaker
和 session 才能保存或检索记录。 Of course you also need to create the table.当然,您还需要创建表。 For example:
例如:
Item.__table__.create(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
item = Item(account_id='a1', name='n1')
item.set_now()
session.add(item)
session.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.