我正在为烧瓶和反应应用程序使用Brian Cappello入门套件。我正在尝试在两个模型之间创建关系,并希望加载相关数据作为对前端的响应。
下面是两个类模型
class UserChatRoom(Model):
sender_id = foreign_key('User')
sender = relationship('User')
listing_id = foreign_key('Listing')
listing = relationship('Listing')
class User(Model, UserMixin):
email = Column(String(50), unique=True, index=True)
name = Column(String(256))
password = Column(String, nullable=True)
pic = Column(String, nullable=True)
active = Column(Boolean(name='active'), default=False)
confirmed_at = Column(DateTime(), nullable=True)
mobile = Column(String(13), unique=True, nullable=False)
is_mobile_verified = Column(Boolean(), default=False)
user_roles = relationship('UserRole', back_populates='user',
cascade='all, delete-orphan')
roles = association_proxy('user_roles', 'role',
creator=lambda role: UserRole(role=role))
buyerDetails = Column(JSON, default={}, nullable=True)
sellerDetails = Column(JSON, default={}, nullable=True)
__repr_props__ = ('id', 'email', 'name', 'mobile', 'active')
下面是我的 UserChatRoom 类序列化程序
USER_CHAT_ROOM_FIELDS = (
"id",
"created_at",
"updated_at",
"listing_id",
"sender_id")
class UserChatRoomSerializer(ModelSerializer):
sender = fields.Nested("UserSerializer", only='name',
dump_only=True)
class Meta:
model = UserChatRoom
fields = USER_CHAT_ROOM_FIELDS
@api.serializer(many=True)
class UserChatRoomListSerializer(UserChatRoomSerializer):
class Meta:
model = UserChatRoom
fields = USER_CHAT_ROOM_FIELDS
这种关系基本上是用户拥有一个给定列表的聊天室。当我查询 UserChatRoom 表时,我需要以下响应。
"data": [
{
"created_at": "2021-08-30T11:47:54.992658+00:00",
"id": 3,
"listing_id": 37,
"sender_id": 27,
"sender": {
"name" : "xxyyyzzz"
},
"updated_at": "2021-08-30T11:47:54.992658+00:00"
}
],
但我得到这个输出
"data": [
{
"created_at": "2021-08-30T11:47:54.992658+00:00",
"id": 3,
"listing_id": 37,
"sender_id": 27,
"updated_at": "2021-08-30T11:47:54.992658+00:00"
}
],
使用的查询:
user_list = UserChatRoom.filter_by(
listing_id=listing_id).all()
当我使用 .first() 时,我可以通过 usr_list.sender 加载发件人详细信息,但对于 .all() 它没有填充