我遇到了这个错误操作数应该包含1列的问题,我知道它们是子查询中的两个字段,但是从我的代码和使用flask-sqlalchemy我无法弄清楚出了什么问题。我正在将我的应用程序从 flask-peewee 转换为 flask-sqlalchemy,这是我无法解决的一个问题。
这里是主要查询代码,第一个是我的新 sql-alchemy 查询,另一个是 peewee 查询。
//SqlAlchmey
return UserBeer.query.filter(or_( UserBeer.id < self.following(), UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5)
//Peewee Query
return UserBeer.select(Beer, UserBeer).join(Beer).where(
(UserBeer.username << self.following()) |
(UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5)
导致问题的查询部分是调用self.following()
如果我删除 sqlalchemy 查询在此处工作是该查询的代码下面是内容self.following()
// SQLAlchmey
return Relationship.query.filter(Relationship.from_user == self)
//Peewee
return ( User.select().join(Relationship, on=Relationship.to_user).where(Relationship.from_user == self))
我知道第二个查询我要求两个不同的东西,但似乎你在 SQLAlchemy 中声明模型中的关系是我认为正确但不确定的关系模型。我的用户模型也不确定是否缺少某些东西。
class Relationship(db.Model):
id = db.Column(db.Integer, primary_key=True)
from_user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
to_user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
from_user = db.relationship('User', backref=db.backref('relationships', lazy='joined'), foreign_keys=from_user_id)
to_user = db.relationship('User', backref=db.backref('related_to', lazy='joined'), foreign_keys=to_user_id)
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(), unique=True)
email = db.Column(db.String(), unique=True)
bio = db.Column(db.String(160))
password = db.Column(db.String(200))
joined_at = db.Column(db.DateTime(), default=datetime.datetime.now)
is_admin = db.Column(db.Boolean(), default=False)
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
编辑 我认为当我再次查看时整个错误可能很有用
OperationalError: (_mysql_exceptions.OperationalError) (1241, 'Operand should contain 1 column(s)') [SQL: u'SELECT user_beer.id AS user_beer_id, user_beer.username_id AS user_beer_username_id, user_beer.beer_id AS user_beer_beer_id, user_beer.rating AS user_beer_rating, user_beer.description AS user_beer_description, user_beer.recommend AS user_beer_recommend, user_beer.tried_date AS user_beer_tried_date \nFROM user_beer \nWHERE user_beer.id < (SELECT relationship.id AS relationship_id, relationship.from_user_id AS relationship_from_user_id, relationship.to_user_id AS relationship_to_user_id \nFROM relationship \nWHERE %s = relationship.from_user_id) OR %s = user_beer.username_id ORDER BY user_beer.tried_date DESC \n LIMIT %s'] [parameters: (1L, 1L, 5)]