gpt4 book ai didi

python - SQLAlchemy 查询表与外键连接

转载 作者:行者123 更新时间:2023-12-04 03:02:16 24 4
gpt4 key购买 nike

我正在尝试通过 Flask-SQLAlchemy 查询显示来自 MySQL 的数据,并将外键 (category_id) 更改为分配给 category_id 的名称。更准确地说 - enter image description here

通过查询,我想显示名称来自类别表的项目,而不是 category_id。

这是我的代码:

class MyEnum(enum.Enum):
piece = "piece"
kg = "kg"

class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(25), nullable=False)

class Product(db.Model):
__tablename__ = 'product'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
quantity = db.Column(db.Integer, nullable=False)
product_type = db.Column(db.Enum(MyEnum), nullable=False)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
description = db.Column(db.String(255))

category = db.relationship("Categ{{user.id}}ory",
backref=('products'))


def __init__(self,name, quantity, product_type, category_id, description):
self.name = name
self.quantity = quantity
self.product_type = product_type
self.category_id = category_id
self.description = description


db.create_all()
db.session.commit()

@app.route('/grocery-list', methods=['GET'])
def display_data():
data = Product.query.all()
category_name = db.session.query(Product).join(Category, Product.category_id == Category.name)
return render_template('query_database.html', data=data, category_name = category_name)

#query_database.html
<body>
{% for user in data %}
<li>{{user.id}}. {{user.name}} {{user.quantity}} {{user.product_type}} Category {{user.category_id}} {{user.description}}</li>
{% endfor %}
{{ category_name }}
</body>

query_Database.html 的结果:

3. Ziemniaczki 2 MyEnum.kg Category 1 Na obiad

SELECT product.id AS product_id, product.name AS
product_name,product.quantity AS product_quantity, product.product_type AS product_product_type, product.category_id AS product_category_id,
product.description AS product_description FROM product INNER JOIN category ON product.category_id = category.name

问题:

1) 如何创建这样的查询?我得到了在纯 SQL 中这应该是什么样子的概述,但我在 SqlAlchemy 的文档中找不到等效项:

select p.name, c.name
from product as p
join category as c
on c.id = p.category_id

2) MyEnum.kg 在那里做什么?如何从此 View 中删除 My.Enum?

编辑 - 成功

只要留下工作代码,如果有人需要的话。

@app.route('/grocery-list', methods=['GET'])
def display_data():
data = db.session.query(Product, Category).join(Category).all()
return render_template('query_database.html', data=data)

{% for user, category in data %}
<li>{{user.id}}. {{user.name}} {{user.quantity}} {{user.product_type}} Category {{user.category.name}} {{user.description}}</li>
{% endfor %}

解决方案

加入表后,在模板文件中需要用

解压category.name的值
{{user.category.name}}  

最佳答案

1) How to create such query? I got overview how should this look like in pure SQL but I can't find equivalent in documentation of SqlAlchemy

以下是一些您可能会觉得有用的链接:

由于您已经定义了 ProductCategory 之间的 ORM 关系,您可以 eager load相关类别以及产品:

data = Product.query.options(db.joinedload(Product.category)).all()

然后您可以在模板中访问 user.category.name 而不会发出新的查询。另一个更像 SQL 的解决方案是获取 Product, Category 元组,这看起来就像您所追求的:

# No need to explicitly define the ON clause of the join, unless you
# really want to. SQLAlchemy examines the foreign key(s) and does what
# needs to be done.
data = db.session.query(Product, Category).join(Category).all()

然后在您的模板中解压结果元组:

<!-- I don't understand why it's called "user" -->
{% for user, category in data %}
...
{% endfor %}

2) What MyEnum.kg is doing out there? How to delete the My.Enum from the this view?

这只是枚举的字符串表示:

In [4]: str(MyEnum.kg)
Out[4]: 'MyEnum.kg'

如果您不满意,您需要修改 {{user.product_type}} 以满足您的需求。您已经使用了 SQLAlchemy Enum类型和一个 PEP-435 - 该列的兼容枚举类:

When using an enumerated class, the enumerated objects are used both for input and output, rather than strings as is the case with a plain-string enumerated type...

关于python - SQLAlchemy 查询表与外键连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com