Flask-SQLAlchemy ArgumentError:对象作为 SQL 文本值不合法



尝试通过SQL-Alchemy执行选择查询时,出现以下错误:

ArgumentError: Object <hello.models.User object at 0x106763210> is not legal as a SQL literal value

models.py

Base = declarative_base()
Base.query = db_session.query_property()
@login_manager.user_loader
def get_user(uid):
    user = User.query.filter_by(id=uid).first()
    return user
#Where code error ocurrs
class User(Base, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))
    email = db.Column(db.String(120), unique=True)
    company = db.Column(db.String(120))
    password = db.Column(db.String(90))
    admin = db.Column(db.Boolean, nullable=False, default=False)

就我而言,我执行了一个具有对象而不是特定值的查询。这就是我得到错误的方式。

user=Users.query.filter_by(id=someid).first()#this was not a problem,

但第二个问题就像

friends=Friends.query.filter_by(user).first()#this is where i got ht problem 

谚语flask-sqlalchemy-argumenterror-object-is-not-legal-as-a-sql-literal-value.

这意味着,那

我正在尝试执行一个具有对象用户的查询,而不是 user.id(或类似的东西,它应该是一个值(

因此,当我意识到这一点时,我将查询更改为

Friends=Friends.query.filter_by(user.id).first()#worked fine

在这里,您必须找到有关您的问题的一些信息:链接

键入系统现在具有针对 SQLAlchemy 传递的特定检查 "可检查"对象,否则它们会是 作为文本值处理。

我在这里遇到了同样的问题:

def increase_relation(cls, previous, current):
    current = DBSession.query(cls).filter_by(left_sound_id=previous, right_sound_id=current).first()
    rate = int((100 - current.weight) - (100 - current.weight) / 1.618)
    DBSession.query(cls).
        filter(cls.left_sound_id==previous).
        filter(cls.right_sound_id==current). # error is here
        update({"weight": cls.weight + rate})

如您所见,我将"current"作为参数并在下一行覆盖它,这是错误的。我以这种方式修复了它:

def increase_relation(cls, previous_id, current_id):
    current_rel = DBSession.query(cls).filter_by(left_sound_id=previous_id, right_sound_id=current_id).first()
    rate = int((100 - current_rel.weight) - (100 - current_rel.weight) / 1.618)
    DBSession.query(cls).
        filter(cls.left_sound_id==previous_id).
        filter(cls.right_sound_id==current_id).
        update({"weight": cls.weight + rate})

检查您的"uid",它的类型是否正确?

最新更新