我遇到了烧瓶棉花糖和SQAlchemy的问题,我不知道如何解决。
我有两个模型:
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
rol = db.Column(db.String(15), nullable=False, default="user")
tasks = db.relationship("Task", backref="user", lazy=True)
def __init__(self, username: str, password: str, rol: str = "user"):
self.username = username
self.password = password
self.rol = rol
class Task(db.Model):
__tablename__ = "task"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=True)
description = db.Column(db.String(255), nullable=False)
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
def __init__(self, title: str, description: str):
self.title = title
self.description = description
self.timestamp = datetime.now()
然后我定义了两个模式:
class UserSchema(ma.ModelSchema):
class Meta:
model = User
load_only = ("password",)
class TaskSchema(ma.ModelSchema):
class Meta:
model = Task
include_fk = True
dump_only = ("timestamp",)
执行User模型的转储时,我只能得到taks_id的列表作为任务,如下所示:
{
"user": {
"id": 3,
"tasks": [
2,
3,
4,
5,
6,
7
],
"username": "dhouard1",
"rol": "admin"
}
}
但是,当我在UserSchema中添加嵌套模式时,例如:
tasks = ma.Nested("TaskSchema")
我有一个空杯子:
{
"user": {
"id": 3,
"rol": "admin",
"username": "dhouard1",
"tasks": {}
}
}
有什么我想念的吗?
答案 0 :(得分:0)
最后,我必须解决这个问题。我将许多参数添加到嵌套模式中,如下所示:
tasks = ma.Nested("TaskSchema", many=True)
现在我得到了完整的结果。
{
"user": {
"rol": "admin",
"username": "dhouard1",
"id": 3,
"tasks": [
{
"description": "descripcion de tarea insertada 2",
"title": "descripcion de tarea insertada 2",
"timestamp": "2019-12-13T13:28:09",
"id": 2
},
{
"description": "descripcion de tarea insertada 2",
"title": "descripcion de tarea insertada 2",
"timestamp": "2019-12-13T13:31:32",
"id": 3
},
{
"description": "descripcion de tarea insertada 2",
"title": "descripcion de tarea insertada 2",
"timestamp": "2019-12-13T13:36:27",
"id": 4
},
{
"description": "descripcion de tarea insertada 2",
"title": "descripcion de tarea insertada 2",
"timestamp": "2019-12-13T14:04:34",
"id": 5
},
{
"description": "descripcion de tarea insertada 3",
"title": "descripcion de tarea insertada 3",
"timestamp": "2019-12-13T14:38:59",
"id": 6
},
{
"description": "descripcion de tarea insertada 3",
"title": "descripcion de tarea insertada 3",
"timestamp": "2019-12-16T11:47:33",
"id": 7
}
]
}
}