使用 REST API 和 Flask-SQLAlchemy 创建一对多关系数据
所以我有 2 个表形成一对多关系
一个主人可以拥有多个宠物
class Owner(db.Model):
__tablename__ = "owner"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
address = db.Column(db.String())
pets = db.relationship('Pet', backref='owner', lazy=True)
def __repr__(self):
return f"Post('{self.id}','{self.name},'{self.items}')"
class Pet(db.Model):
__tablename__ = "pets"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
age = db.Column(db.Integer)
owner_id = db.Column(db.Integer, db.ForeignKey('owner.id'), nullable=False)
def __repr__(self):
return f"Post('{self.id}','{self.name}','{self.owner_id}')"
,其中一个 API 调用是创建一只宠物:
@app.route("/createPet", methods=["POST"])
def create_pet():
json_data = request.get_json()
print(json_data)
new_pet = Pet(name = json_data["name"], age = json_data["age"], owner = json_data["owner"])
db.session.add(new_pet)
db.session.commit()
response = "new pet added" + str(json_data)
return response
然后我发布一个 json 正文(主人已经在数据库中)
{
"name":"Snowball 2",
"age":4,
"owner":"homer"
}
但是,当运行时,尝试从以下位置输入宠物时,应用程序看起来会崩溃: json 值
当使用flask-sqlalchemy 时,您可以逃脱从一个对象创建的宠物,其中一个值反向引用另一个模型(例如所有者模型)
owner = (name=”homer, address=”42 evergreen terrace”)
pet = (name=”snowball 2”, age=4, owner=”homer”)
我假设“new_pet”数据库对象有问题但我不确定如何修复 json 的读取/运行方式
So i’ve got 2 tables that form a one-to-many relationship
A owner can own multiple pets
class Owner(db.Model):
__tablename__ = "owner"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
address = db.Column(db.String())
pets = db.relationship('Pet', backref='owner', lazy=True)
def __repr__(self):
return f"Post('{self.id}','{self.name},'{self.items}')"
class Pet(db.Model):
__tablename__ = "pets"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
age = db.Column(db.Integer)
owner_id = db.Column(db.Integer, db.ForeignKey('owner.id'), nullable=False)
def __repr__(self):
return f"Post('{self.id}','{self.name}','{self.owner_id}')"
And one of the API calls is to create a pet:
@app.route("/createPet", methods=["POST"])
def create_pet():
json_data = request.get_json()
print(json_data)
new_pet = Pet(name = json_data["name"], age = json_data["age"], owner = json_data["owner"])
db.session.add(new_pet)
db.session.commit()
response = "new pet added" + str(json_data)
return response
I then POST a json body (the owner is already in the database)
{
"name":"Snowball 2",
"age":4,
"owner":"homer"
}
However, when run it looks like the application crashes when trying to input a pet from a json value
When using flask-sqlalchemy, you could get away with a pet being created from a object where one of the values is backreferencing another model (such as the owner model)
owner = (name=”homer, address=”42 evergreen terrace”)
pet = (name=”snowball 2”, age=4, owner=”homer”)
I'm assuming the “new_pet” db object is at fault but im not sure how to fix how the json is being read / run
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法是传入所有者的唯一标识符,例如数据库中的主键。然后,您可以在视图函数中查询所有者并将它们添加到一对多关系中。
工作示例:
或者,您可以将主人添加到宠物中,如下所示。请注意,所有者正在引用 sqlalchemy 模型对象。
new_pet = Pet(name=json_data["name"],age = json_data["age"],owner=owner)
或者您可以直接保存所有者 ID
One approach is to pass in a unique identifier for the owner e.g their primary key in the database. In your view function you can then query the owner and add them to the one to many relationship.
Working example:
Alternatively, you can add the owner to pets like below. Note that owner is referencing a sqlalchemy model object.
new_pet = Pet(name=json_data["name"], age = json_data["age"], owner=owner)
Or you could save the owner id directly