我目前正在尝试创建许多具有一对多关系的表并将它们序列化,以便我可以将它们公开给我的前端。 我之前找到了一个序列化解决方案,即在每个类中创建一个 serialize() 方法。但是,由于我有一些一对多关系,因此我不确定在使用列表时如何访问其中每个关系的序列化属性。 这是一个类的示例
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped, relationship
from typing import List
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "user_account"
id: Mapped[int] = mapped_column(primary_key=True)
first_name: Mapped[str]
last_name: Mapped[str]
email_address: Mapped[str]
phone_number: Mapped[str]
company: Mapped["Company"] = relationship(back_populates="user")
courses: Mapped[List["Course"]] = relationship(back_populates="user")
def serialize(self):
return {
"id": self.id,
"firstName": self.first_name,
"lastName": self.last_name,
"emailAddress": self.email_address,
"phoneNumber": self.phone_number,
"company": self.company.serialize(), ## This works because it is a 1-1 relationship and I can directly access the serialize method on the company instance
# "courses": self.courses ## Here I can't access the property because it is of type List and not of type Course
}
我已经尝试过简单地循环它,就像您在普通列表中所做的那样
serialized_courses = []
for course in courses:
serialized_courses.append(course.serialize())
但是这不起作用。有人可以帮忙吗?
要序列化 SQLAlchemy ORM 对象列表,您可以使用列表理解。在列表理解中,您可以对
.serialize()
中的每个 course
对象调用 self.courses
方法。以下是修改 serialize
类的 User
方法的方法:
def serialize(self):
return {
"id": self.id,
"firstName": self.first_name,
"lastName": self.last_name,
"emailAddress": self.email_address,
"phoneNumber": self.phone_number,
"company": self.company.serialize(),
"courses": [course.serialize() for course in self.courses]
}
在此
serialize
方法中,course.serialize() for course in self.courses
是一个列表理解,它对 serialize()
中的每个 course
对象调用 self.courses
。结果是序列化的 course
对象的列表。这是假设 Course
类具有与 serialize
类类似的 User
方法。
这应该允许您序列化
User
对象,包括其相关的 Course
对象。