Flask Schema没有使用传递给它的所有数据



让我回溯一下-问题实际上发生在使用我们现有的MentorSchema初始化Mentor时:

class Mentor(db.Model):
__tablename__ = 'mentors'
id = db.Column(db.Integer, primary_key=True)
id_project42 = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
id_user42 = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
finalmark = db.Column(db.Integer, nullable=False, server_default=0)
totalappointments = db.Column(db.Integer, nullable=False, server_default=0)
def __init__(self, id_project42, id_user42, finalmark):
self.id_project42 = id_project42
self.id_user42 = id_user42
self.finalmark = finalmark
self.totalappointments = 0
class MentorSchema(ma.ModelSchema):
class Meta:
model = Mentor

因此,如果我有d = { "id_project42": 101, "id_user42": 57, "finalmark": 86},并且我尝试mentor_schema.dump(d),那么id_project42和id_user42都消失了,我得到一个错误,告诉我:TypeError: __init__() missing 2 required positional arguments: 'id_project42' and 'id_user42'

我们使用的实际代码如下:

class ApiUserInit(Resource):
def post(self, userId):
data = Api42.userProjects(userId)    # Returns a list of dicts
if data is None:
return formatError('Error', 'No projects found for user')
for d in data:
print(d)    # prints {"id_project42": 101, "id_user42": 57, "finalmark": 86}
mentor_schema = MentorSchema()
newMentor, errors = mentor_schema.load(d) # Only loading the "finalmark"!!!!!!
if errors:
return internalServiceError()
db.session.add(newMentor)
db.session.commit()
return {"status":"mentor initialization successful"}, 201

如果我使用模式的方式也有问题,请告诉我。

默认情况下,当您调用架构的转储方法时,将不包括外键。您需要在模式Metaclass:上设置include_fk = True

class MentorSchema(ma.ModelSchema):
class Meta:
model = Mentor
include_fk = True

更多信息:棉花糖-sqlalchemy API参考

相关内容

  • 没有找到相关文章

最新更新