我在数据库中的表之间有一对多的关系,我想使用API来获取数据。 我认为ma.Nested不起作用,因为我没有掌握所有领域 有人可以帮我吗?
我只有这个: [ { “ IsRef”:否, “命令”:[ “ 299d7f0b-721c-484b-9448-072716a5fd70”, “ 382c5d9f-99a1-4aa2-ac30-96084e202fad”, “ 299d7f0b-721c-484b-9448-072716a5fd75”, “ 382c5d9f-99a1-4aa2-ac30-96084e202fak” ], “ filename”:“ uiyg”, “版本”:8 } ]
这是数据库模型:
class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(255), unique=True)
version = db.Column(db.Integer, unique=True)
IsRef = db.Column(db.Boolean)
commands = db.relationship('Command', backref='log', lazy='joined')
def __init__(self, filename, version, IsRef):
self.filename = filename
self.version = version
self.IsRef = IsRef
class Command(db.Model):
id_command = db.Column(db.String(255), primary_key=True, autoincrement=False)
name = db.Column(db.String(255))
log_id = db.Column(db.Integer, db.ForeignKey('file.id'))
status = db.Column(db.Boolean)
events = db.relationship('Event', backref='com', lazy='joined')
def __init__(self, id_command, name, log_id, status):
self.id_command = id_command
self.name = name
self.log = log_id
self.status = status
class Event(db.Model):
id_event = db.Column(db.Integer, primary_key=True)
event_name = db.Column(db.String(255))
seq_number = db.Column(db.Integer)
com_id = db.Column(db.Integer, db.ForeignKey('command.id_command'))
def __init__(self, event_name, seq_number, com_id):
self.event_name = event_name
self.seq_number = seq_number
self.com = com_id
这是架构:
class EventSchema(ma.ModelSchema):
class Meta:
model = Event
fields = ('event_name', 'seq_number')
class CommandSchema(ma.ModelSchema):
class Meta:
model = Command
events = ma.Nested(EventSchema)
fields = ('id_command', 'name', 'status', 'events')
class LogSchema(ma.ModelSchema):
class Meta:
model = File
commands = ma.Nested(CommandSchema)
fields = ('filename', 'version', 'IsRef', 'commands')
Log_schema = LogSchema(many=True)
这是API:
@app.route("/getall/<version>", methods=["GET"])
def get_all(version):
alle = File.query.filter_by(version=version)
return Log_schema.jsonify(alle)
答案 0 :(得分:0)
这个问题解决了。我已将'lazy ='joined'更改为'lazy ='dynamic',并将ma.Nested排除在Meta类之外