Flask应用访问外键值触发AttributeError:'int'对象无'username'属性
解决Flask购物车接口中AttributeError: 'int' object has no attribute 'username'
问题根源
你的Cart模型里user字段只是普通的Integer类型,没有和User模型建立ORM关联关系。查询购物车数据时,c.user返回的是存储的用户ID(整数),而非User对象,所以调用.username会触发属性错误。
解决方案
方案1:修正模型,建立ORM外键关联(推荐)
如果使用SQLAlchemy,修改Cart模型,通过ForeignKey和relationship关联User模型,让ORM自动帮你关联查询用户对象:
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) # 反向引用,方便从User实例查询关联的购物车 carts = db.relationship('Cart', backref='user', lazy=True) class Cart(db.Model): id = db.Column(db.Integer, primary_key=True) # 替换原Integer字段,用ForeignKey关联User表的id字段 user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) # 建立关系,让c.user直接返回对应的User对象 user = db.relationship('User') products = db.Column(db.PickleType) # 根据你的实际字段类型调整
修改后,原来的序列化代码就能正常工作:
return jsonify([{'products': c.products, "user": c.user.username} for c in cart])
方案2:临时手动查询用户(不推荐,仅兼容旧场景)
如果暂时无法修改模型,可以在序列化时手动通过用户ID查询User对象:
cart_data = [] for c in cart: # 通过用户ID查询User实例 user = User.query.get(c.user) cart_data.append({ 'products': c.products, 'user': user.username if user else 'Unknown User' }) return jsonify(cart_data)
注意
优先选择方案1,建立ORM关联是SQLAlchemy的最佳实践,能简化后续的关联查询、级联操作等场景,避免重复的手动查询逻辑。
内容的提问来源于stack exchange,提问作者Sins97
相关产品推荐
相关产品推荐

