从SQLAlchemy基类生成JSON,包括关系中的子类

时间:2017-06-27 11:16:30

标签: python json python-3.x sqlalchemy

我试图生成我的SQLAlchemy类的JSON,我按照这个例子: https://blogs.gnome.org/danni/2013/03/07/generating-json-from-sqlalchemy-objects/

它工作得非常好,但现在我想要包含SQLAchemy关系生成的子类的所有数据。我已经尝试过几个方面,最后一个尝试迭代子类,但我不知道方法子类为什么不返回任何东西。这是tojson修改的函数:

def tojson(self):
    res=self.columnitems
    for cls in self.__class__.__subclasses__():
        res[cls.__name__]=cls.tojson()
    return res

你知道怎么办?

提前致谢

1 个答案:

答案 0 :(得分:0)

我暂时无法发表评论,但根据所提供的信息,我假设您正在尝试从(相关的)sqlalchemy课程中生成json。你可以使用棉花糖(https://marshmallow.readthedocs.io/en/latest/)。

下面的(快速)示例显示了如何使用两个相关表格的marshmallow生成json。

from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()


# Creating dummy classes...
class Owner(Base):
    __tablename__ = 'owner'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(250))
    interested_in_cars = Column('interest', Boolean)
    car = relationship('Car', uselist=False, back_populates="owner")

    def __init__(self, name, interested_in_cars, id):
        self.id = id
        self.name = name
        self.interested_in_cars = interested_in_cars

    def __repr__(self):
        return '< (id={id}) Owner: {name} - interested: {interested_in_cars} >'.format(id=self.id,
                                                                                       name=self.name,
                                                                                       interested_in_cars=self.interested_in_cars)


class Car(Base):
    __tablename__ = 'car'
    id = Column('id', Integer, primary_key=True)
    brand = Column(String(250))
    owner_id = Column(Integer, ForeignKey('owner.id'))
    owner = relationship('Owner', back_populates='car')

    def __init__(self, owner_id, brand):
        self.owner_id = owner_id
        self.brand = brand

    def __repr__(self):
        return '< Owner: {owner_id} - Car: {brand} >'.format(owner_id=self.owner_id, brand=self.brand)


engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
ex_ses = session()
Base.metadata.create_all(engine)

owner_1 = Owner(interested_in_cars=True, name='Owner a', id=1)
owner_2 = Owner(interested_in_cars=False, name='Owner b', id=2)
ex_ses.add(owner_1)
ex_ses.add(owner_2)

# ID's - quick example
car_1 = Car(owner_id=1, brand='Car a')
car_2 = Car(owner_id=2, brand='Car b')
ex_ses.add(car_1)
ex_ses.add(car_2)

ex_ses.commit()

# Using marshmallow to generate the json
from marshmallow import Schema, fields, pprint


class OwnerShema(Schema):
    id = fields.Int()
    name = fields.String()
    interested_in_cars = fields.Boolean()
    car = fields.Nested('CarShema')


class CarShema(Schema):
    id = fields.Int()
    brand = fields.String()


# Example Owners and cars
owners_cars = ex_ses.query(Owner).all()
print('Owners and cars: ', owners_cars)
owners_cars_shema = OwnerShema()
pprint(owners_cars_shema.dump(owners_cars, many=True).data)

有关更多信息,请参阅marshmallow文档(上面提供的链接)。