ForeignKey序列化为空字典,不填充数据



我有两个模型Profile &代表一对多关系的产品。一个配置文件可以有许多产品。我序列化了所有的字段。具有ForeignKey的列将输出为空字典。下面的模型将使我的问题更清楚。

from backend_olx import db
from marshmallow import Schema, fields
from datetime import datetime
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
created_by = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=False)
purchased_by = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=True)
name = db.Column(db.String(50), nullable=False)
price = db.Column(db.Integer, nullable=False)
description = db.Column(db.Text, nullable=False)
def __repr__(self):
return '<Product Name %r>' % self.name
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
email = db.Column(db.String(100), nullable=False, unique=True)
products_sold = db.relationship('Product', backref='profile_sold', foreign_keys="Product.created_by",lazy=True)
products_purchased = db.relationship('Product', backref='profile_purchased', foreign_keys="Product.purchased_by",lazy=True)
def __repr__(self):
return '<User %r>' % self.username
class ProfileSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
email = fields.Str()
products_sold = fields.Nested('ProductSchema', many=True)
products_purchased = fields.Nested('ProductSchema', many=True)

class ProductSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.Str()
price = fields.Int()
created_by = fields.Nested('ProfileSchema')
purchased_by = fields.Nested('ProfileSchema')

profile_schema = ProfileSchema()
profiles_schema = ProfileSchema(many=True)
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)

ProfileSchema中的Nested()方法按预期工作,但它在ProductSchema中给出{}。我希望created_by和purchased_by字段也被填充。

怎么做呢?

您不能仅仅传递一个外键并期望Nested知道如何处理它。你需要传递一个关系。

为两个字段创建一个关系,并在模式中使用关系名称。

我通常使用xxx_id作为列名,xxx作为关系名。

class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
created_by_id = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=False)
purchased_by_id = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=True)
name = db.Column(db.String(50), nullable=False)
price = db.Column(db.Integer, nullable=False)
description = db.Column(db.Text, nullable=False)
# Setup relations here
created_by = db.relationship(...)
purchased_by = db.relationship(...)

class ProductSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.Str()
price = fields.Int()
created_by = fields.Nested('ProfileSchema')
purchased_by = fields.Nested('ProfileSchema')

最新更新