SQLAlchemy使用where约束选择

2024-06-03 12:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从数据库中获取表的子集。数据库是MySql数据库。你知道吗

Python代码:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, VARCHAR, DATETIME, INT, TEXT, TIMESTAMP
from datetime import datetime
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
class TrackablesTable(Base):
        __tablename__ = 'Trackables'

        trackableId = Column(INT, primary_key=True) #autogenerate
        productID = Column(TEXT)
        createdOn = Column(TIMESTAMP) #autogenerate
        urlTitle = Column(TEXT)
        humanTitle = Column(TEXT)
        userId = Column(VARCHAR(45))


        def __repr__(self):
                return "<MyTable(%s)>" % (self.asin)

        @staticmethod
        def getTrackableByProductId(productID, session):
            trackable = session.query(TrackablesTable).filter_by(productID=productID)
            return trackable

注意底部的方法。我希望这个方法能得到“Trackables”表中的所有行,其中的“productID”列具有productID变量的值。相反,它似乎返回了一个格式错误的查询。你知道吗

它返回的查询如下:

SELECT "Trackables"."trackableId" AS "Trackables_trackableId", "Trackables"."productID" AS "Trackables_productID", "Trackables"."createdOn" AS "Trackables_createdOn", "Trackables"."urlTitle" AS "Trackables_urlTitle", "Trackables"."humanTitle" AS "Trackables_humanTitle", "Trackables"."userId" AS "Trackables_userId" 
FROM "Trackables" 
WHERE "Trackables"."productID" = :productID_1

MySQL workbench告诉我查询的格式不正确。此外,productID查询中的值(“:productID\u 1”)不是代码中引用的变量的实际值。你知道吗


Tags: textfromimport数据库sqlalchemyascolumnuserid
1条回答
网友
1楼 · 发布于 2024-06-03 12:22:34

您需要执行查询,而不仅仅是返回它。在对其调用all()first()scalar()等方法或对其进行迭代之前,查询一直是查询对象。你知道吗

您的方法应如下所示:

@staticmethod
def getTrackableByProductId(productID, session):
    q = session.query(TrackableTable).filter_by(productID=productID)
    return q.first()

打印查询时,SQLAlchemy使用格式占位符而不是实际值来显示查询。实际的查询是由dbapi(比如pythonmysql)在SQLAlchemy的控制之外构建的。你知道吗


旁注:您的代码,包括staticmethod的使用和命名约定,看起来像是您试图复制一个Java类。考虑阅读PEP8

相关问题 更多 >