让我稍微回溯一下-问题实际上是在使用我们拥有的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
请告知我使用模式的方式是否存在问题。
答案 0 :(得分:0)
默认情况下,调用架构的转储方法时将不包含外键。您需要在架构include_fk = True
类上设置Meta
:
class MentorSchema(ma.ModelSchema):
class Meta:
model = Mentor
include_fk = True