使用 REST API 和 Flask-SQLAlchemy 创建一对多关系数据

发布于 2025-01-10 16:34:08 字数 1533 浏览 0 评论 0原文

所以我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

○闲身 2025-01-17 16:34:08

一种方法是传入所有者的唯一标识符,例如数据库中的主键。然后,您可以在视图函数中查询所有者并将它们添加到一对多关系中。

工作示例:

# Payload:
{
    "name":"Snowball 2",
    "age":4,
    "owner_id":1
}


@app.route("/createPet", methods=["POST"])
def create_pet():
    json_data = request.get_json()

    owner = Owner.query.get(json_data["owner_id"])
    if owner is None:
      abort(400, description="Owner not found")

    new_pet = Pet(name=json_data["name"], age = json_data["age"])
    owner.pets.append(new_pet)
    db.session.commit()

    response = "new pet added" + str(json_data)

    return response

或者,您可以将主人添加到宠物中,如下所示。请注意,所有者正在引用 sqlalchemy 模型对象。

new_pet = Pet(name=json_data["name"],age = json_data["age"],owner=owner)

或者您可以直接保存所有者 ID

new_pet = Pet(name=json_data["name"], age = json_data["age"], owner_id=json_data["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:

# Payload:
{
    "name":"Snowball 2",
    "age":4,
    "owner_id":1
}


@app.route("/createPet", methods=["POST"])
def create_pet():
    json_data = request.get_json()

    owner = Owner.query.get(json_data["owner_id"])
    if owner is None:
      abort(400, description="Owner not found")

    new_pet = Pet(name=json_data["name"], age = json_data["age"])
    owner.pets.append(new_pet)
    db.session.commit()

    response = "new pet added" + str(json_data)

    return response

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

new_pet = Pet(name=json_data["name"], age = json_data["age"], owner_id=json_data["owner_id"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文