我有三个SQLalchemy
表,它们之间有一对多关系。我的表定义如下:
汽车→图1:n和形象→CarPart 1: n
class Car(Base):
__tablename__ = 'cars'
car_id = Column(String(36), primary_key=True)
license_plate = Column(String(12))
def __init__(self, car_id=None, license_plate=None):
self.car_id = car_id
self.license_plate = license_plate
class Image(Base):
__tablename__ = 'images'
image_id = Column(String(36), primary_key=True)
car_id = Column(ForeignKey('cars.car_id'))
angle = Column(String(12))
car = relationship('Car', uselist=True)
def __init__(self, image_id=None, car_id=None, angle=None):
self.image_id = image_id
self.car_id = car_id
self.angle = angle
class CarPart(Base):
__tablename__ = 'car_parts'
part_id = Column(String(36), primary_key=True)
car_id = Column(ForeignKey('cars.car_id'))
image_id = Column(ForeignKey('images.image_id'))
part_type = Column(String(20))
car = relationship('Car', uselist=True)
image = relationship('Image', uselist=True)
def __init__(self, part_id=None, car_id=None, image_id=None, part_type=None):
self.part_id = part_id
self.car_id = car_id
self.image_id = image_id
self.part_type = part_type
如果我使用db.query(Car, Image, CarPart)
对特定的car_id
或license_plate
进行查询,我希望在嵌套字典中接收属于该汽车的所有信息,例如
{
'car_id': '001',
'license_plate': 'AA-000-B'
'images': [{
'image_id': '0001',
'angle': 'front',
'car_parts': [{
'part_id': '00001',
'part_type': 'bumper'
},
{
'part_id': '00002',
'part_type': 'window'
}]
},
{
'image_id': '0002'
'angle': 'rear'
'car_parts': [{
'part_id': '00003',
'part_type': 'door'
},
{
'part_id': '00004',
'part_type': 'wheel'
}]
}]
}
}
我希望在SQLAlchemy中找到一些可以做到这一点的内置方法,但到目前为止我找不到。有什么好的、简洁的方法可以做到这一点吗?或者我是否需要将db.query().all()
返回的列表手动转换为字典?
通过在表定义中添加字段,我能够在执行查询时获得嵌套结构。在我的表定义中,现在有:
class Car(Base):
__tablename__ = 'cars'
car_id = Column(String(36), primary_key=True)
license_plate = Column(String(12))
car_images = relationship('Image', back_populates=True)
def __init__(self, car_id=None, license_plate=None):
self.car_id = car_id
self.license_plate = license_plate
和其他表中的类似内容。这将为我提供嵌套列表,可以很容易地将其转换为嵌套字典。