如何在Python中获取Model内对象列表的值?(一对多关系场景)
Hey there! I see you're working with a one-to-many relationship between User and Friend models, and you're stuck with those generic <models.Friend object at ...> references when printing the friends field. Let's fix that so you can see actual, meaningful data instead.
方法1:遍历关系列表,提取具体属性
Since record.friends is a list of Friend model instances, you can loop through each one and access its individual attributes (like id, name, or whatever fields you've defined on the Friend model). Here's a clean way to format the data with a list comprehension:
record = User.query.filter_by(id=7).first() # 替换成你的Friend模型实际拥有的字段,比如id、name、email等 formatted_friends = [{"id": friend.id, "name": friend.name} for friend in record.friends] # 现在打印就能看到具体值了 print('|{}|{}|{}'.format(record.rfc, record.name, formatted_friends))
方法2:自定义Friend模型的__repr__方法
If you want the default print output of Friend objects to show useful details instead of memory addresses, you can override the __repr__ method in your Friend model. This will make any print of a Friend instance (or list of instances) display the info you care about automatically:
from flask_sqlalchemy import SQLAlchemy # 或者你使用的SQLAlchemy导入方式 db = SQLAlchemy() class Friend(db.Model): __tablename__ = 'friends' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) # 其他字段... user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # 关联User的外键 def __repr__(self): # 自定义显示内容,替换成你的实际字段 return f"<Friend id={self.id} name='{self.name}'>"
After adding this, your original print statement will output something like:
|BDS344XX3343|Bob|[
, ]
为什么会显示对象引用?
By default, printing a Python object shows its class name and memory address. SQLAlchemy relationship attributes return lists of model instances, which is why you're seeing those <models.Friend object ...> entries. The two methods above let you either explicitly extract the data you need, or change how the objects are displayed by default.
内容的提问来源于stack exchange,提问作者Alex

