【问题标题】:Generating JSON from SQLAlchemy base class including subclases from relationship从 SQLAlchemy 基类生成 JSON,包括来自关系的子类
【发布时间】:2017-11-30 10:13:54
【问题描述】:

我正在尝试生成我的 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

你知道有什么方法吗?

提前致谢

【问题讨论】:

  • 关系不是子类。
  • 那么我该如何迭代关系呢?

标签: python json python-3.x sqlalchemy


【解决方案1】:

我还不能发表评论,但根据提供的信息,我假设您正在尝试从您的(相关)sqlalchemy 类生成一个 json。为此,您可以使用棉花糖 (https://marshmallow.readthedocs.io/en/latest/)。

下面的(快速)示例展示了如何使用两个相关表的棉花糖生成 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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2012-10-06
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多