【问题标题】:Flask SQLAlchemy Foreign Key QueryingFlask SQLAlchemy 外键查询
【发布时间】:2017-08-28 06:16:02
【问题描述】:

我对 Python 和一般编程很陌生。我可以在逻辑方面使用一些帮助。

我有 3 个表,用户、帖子、cmets。表 cmets 有一列“user_id”,它有一个指向用户列“id”的 Foreign_Key。也作为 post_id 与 FK 到 post_id。

cmets.user_id = users.id && cmets_post_id = posts.id

要查询我正在使用的特定帖子:

post = Posts.query.filter_by(id=post_id).first_or_404()

查询我正在使用的 cmets:

comments = Comments.query.filter_by(post_id=post_id).order_by(Comments.time.desc()).all()

我想从 cmets.user_id.... 所在的 users 表中获取用户名。这是我的逻辑被打乱的地方。

使用FK可以直接引用Users.username吗?或者 FK 是否只是映射关系,以便我可以运行查询。其中 cmets.user_id = Users.id .... 获取用户名和所有内容。我觉得我这样做效率很低。

我想用“Users.username where comment.user_id = user_id”替换comment.user_id

{% if comments %}
  {% for comment in comments %}
    {{ comment.user_id }}
    {{ comment.time }}
    {{ comment.comment }}
  {% endfor %}
{% endif %}

我认为我需要在 cmets 中创建一个新列 cmets.user_username 并为其指定 users.username 的 FK。我不断收到 150 错误,并且列是相同的。相同的排序规则、数据类型和长度。

【问题讨论】:

  • 您通常会将用户表 JOIN 到您的评论中,以便同时获取该数据。 SQLAlchemy relationships 提供 ORM 端,并且可以使用连接来急切地加载数据。例如,如果您要在 Users 和 Comments 之间配置关系,则可以使用 joinedload(Comments.user) 等。
  • 太好了,你帮了大忙。谢谢!

标签: flask sqlalchemy flask-sqlalchemy


【解决方案1】:

您可以定义一个属性类型为 SQLAlchemy 的relationship 如下:

class Comment(db.Model):
    id = db.Column(db.Integer(), primary_key=1)
    content = db.Column(db.Text(), nullable=0)
    create_user_id = db.Column(db.Integer(), db.ForeignKey("user.id"))
    create_user = db.relationship("User", foreign_keys=create_user_id)
    post_id = dn.Column(db.Integer(), db.ForeignKey("post.id"))

你可以在模板文件中写comment.create_user.username。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 2017-05-24
    • 1970-01-01
    • 2014-04-21
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多