棉花糖序列化对象如何接收嵌套的连接表对象?

时间:2018-09-29 00:43:01

标签: python sqlalchemy foreign-keys schema marshmallow

我用棉花糖,烧瓶和sqlachemy来构建项目:

我的模式和模型是:

class Category(db.Model):
    __tablename__ = 'Category'
    id = db.Column(postgresql.UUID(as_uuid=True), primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    products = relationship("Product", back_populates='category')

class Product(db.Model):
    __tablename__='Product'
    id = db.Column(postgresql.UUID, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    desc = db.Column(db.TEXT, nullable=True)
    provider = db.Column(db.String(200), nullable=False)
    barcode = db.Column(db.String(20), nullable=False)
    price = db.Column(db.DECIMAL(10, 2), nullable=False)
    category_id=db.Column(postgresql.UUID, db.ForeignKey('Category.id'))
    category = relationship("Category", back_populates='products')

class CategorySchema(ModelSchema):
    class Meta:
        model = Category
        sqla_session=db.session


class ProductSchema(ModelSchema):
    class Meta:
        model = Product
        sqla_session=db.session

您可以看到产品具有外键category_id

我得到request(product)json,例如:

{
 "id": "fceeec0d-de3c-4d65-84ff-f2374cf87e02",
 "name": "Iron Screwdriver",
 "provider": "ABC provider",
 "barcode": "e9099384-7e67-45e3-88d5-8b310b40d0aa",
  "price": 10.5,
  "category_id": "a0b98a09-e7a4-4898-af70-7f3bd403678d"
 }

我想保存到产品到数据库中,前提是已经有类别具有相应的category_id。

我想将此产品保存为:

def create(product):
    id=product['id']
    existing_item = Product.query.filter(Product.id == id).one_or_none()
    if id is None:
        id = uuid.uuid4()
        product['id']=id
    if existing_item is None:
        schema = ProductSchema()
        new_item = schema.load(product, session=db.session).data
        print(new_item)
        print(dir(new_item))
        db.session.add(new_item)
        db.session.commit()
        data = schema.dump(new_item).data
        return data, 201

但是我发现new_item就像:

 {'provider': 'ABC provider', 'name': 'Iron Screwdriver', 'price': Decimal('10.50'), 'id': UUID('fceeec0d-de3c-4d65-84ff-f2374cf87e02')}

在new__item中没有外键category_id。 如何获取(创建)具有类别连接的ProductSchema并保存它。 向我展示示例如何执行此操作。

0 个答案:

没有答案