0

该问题类似于Flask Marshmallow 关系仅转储 id如何构造一个 API 端点,外键替换为它们的值?. 但不幸的是,参考这些问题的答案对我没有多大帮助。

我是第一次练习使用 Flask_Marshmallow。我创建了两个数据库模型,“Store”和“StoreItems”。Store 表示一对多关系中的 Parent 表,其中每个 store 可以有多个 time 和多个相同 item。但是,返回的 JSON 字符串仅显示项目的关联 store_id。我想显示项目本身的名称。

模型.py

class Store(db.Model):
    __tablename__ = "stores"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False)

    items = db.relationship('StoreItem', backref=backref('store_items', cascade="all, delete"))
    
    def __repr__(self):
        return "<Store: {}>".format(self.name)
        
    # def serialize_store(self):
    #     return {
    #         'id': self.id,
    #         'name': self.name
    #     }

class StoreItem(db.Model):
    __tablename__ = "store_items"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False)
    price = db.Column(db.Float, nullable=False)
    store_id = db.Column(db.Integer, db.ForeignKey('stores.id'))
    # store = db.relationship('Store')
    
    

    def __repr__(self):
        return "<StoreItem: {}>".format(self.name)

    # def serialize_store_item(self):
    #     return {
    #         "id": self.id,
    #         "name": self.name,
    #         "price": self.price,
    #         "store_id": self.store_id
    #     }
    
class StoreSchema(ma.SQLAlchemySchema):
    class Meta:
        model = Store

    id = ma.auto_field()
    name = ma.auto_field()
    items = ma.Nested(StoreItemSchema, many=True)
    

class StoreItemSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = StoreItem
        include_fk = True

种子.py


s1 = Store(name='Amazon')    
s2 = Store(name='Ebay') 
s3 = Store(name='Walmart')

si1 = StoreItem(name='Pant', price=10.00, store_id=1)
si2 = StoreItem(name='Shirt', price=15.00, store_id=1)
si3 = StoreItem(name='T-Shirt', price=5.00, store_id=1)
si4 = StoreItem(name='Jeans', price=20.00, store_id=2)
si5 = StoreItem(name='Shoes', price=10.00, store_id=3) 
si6 = StoreItem(name='Socks', price=5.00, store_id=3)

print(si1)




db.session.add_all([s1, s2, s3, si1, si2, si3, si4, si5, si6])
db.session.commit()

结果:

{
    "stores": [
        {
            "id": 1,
            "items": [
                1,
                2,
                3
            ],
            "name": "Amazon"
        },
        {
            "id": 2,
            "items": [
                4
            ],
            "name": "Ebay"
        },
        {
            "id": 3,
            "items": [
                5,
                6
            ],
            "name": "Walmart"
        }
    ]
}

我期待这个:


{
    "stores": [
        {
            "id": 1,
            "items": [
                "Pant",
                "Shirt",
                "T-Shirt"
            ],
            "name": "Amazon"
        }

  }
4

0 回答 0