【问题标题】:How do I Access One Column of a Peewee ForeignKeyField如何访问 Peewee ForeignKeyField 的一列
【发布时间】:2016-03-22 13:58:18
【问题描述】:

我正在尝试通过我的 Like 表使用各种查询将 ForeignKeyField 的 id 列访问到我的 UserAccount 表,例如: if models.Like.select().where(models.Like.user.id==current_user.id,models.Like.post.id==post_id).exists():

我一直在尝试访问用户和帖子上的列 ID。我之前在 Jinja 模板中通过循环每一行并通过model.Table.foreignkeyfield.foreignkeycolumn 访问外键来实现这一点,如下所示:

{% for post in posts %}
    {{post.user.username}}
{% endfor %}

(user是ForeignKeyField,username是User表中的一列)

我的问题是:有没有办法让我在不遍历整个表的情况下访问外键列???

“喜欢”模型

class Like(Model):
    post = ForeignKeyField(rel_model=Post, related_name='Like')
    user = ForeignKeyField(rel_model=UserAccount, related_name='Like')

    class Meta:
        database = db

非常感谢 - 汤姆

【问题讨论】:

    标签: python mysql flask peewee flask-peewee


    【解决方案1】:

    你不需要使用id列,peewee应该可以在查询中弄清楚:

    (Like
     .select()
     .where(
         (Like.user==current_user) &
         (Like.post == post_id)).exists():
    

    【讨论】:

    • 酷 - 只是出于兴趣,假设我想通过这种方法选择不同的列(如 UserAccount 表的用户名列,我将如何实现?)
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 2015-07-14
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多