从查看web2py查询数据库

时间:2016-03-21 16:03:17

标签: web2py web2py-modules

我正在尝试从web2py中的视图查询数据库表,因为我需要从另一个表中为当前表中的每一行取一个字段,所以我编写了这样的代码:

{{for recipe in rows:}}

<div class="well">
    <table>
        <tr>
            <td>
             <div style="text-align:center">
<img width="200px"
     src="{{=URL('download', args=db(db.uploads.recipe_id==recipe.id).select().first().up_file)}}" />
</div>

            </td>
            <td><button>
            -
            </button></td><td><span class='votes'>{{=recipe.votes}}</span></td><td><button>
            +
            </button><td><strong>{{=A("comments",_href=URL('view_posts',args=recipe.id))}},{{=recipe.name}}</strong></td></td></tr>
    </table>

</div>
{{pass}}

但我怀疑我们是否可以从视图中查询数据库? 如果不是,我如何从控制器查询相同的内容并将其返回到视图? 这可能是一个愚蠢的怀疑,但对不起,我是web2py的新手

1 个答案:

答案 0 :(得分:1)

可以这样做,但效率不高,因为你将对表中的每一行都有一个单独的查询。相反,您在控制器中创建rows对象的查询应该涉及与db.uploads表的连接:

    rows = db((your_current_query) & (db.uploads.recipe == db.recipe.id)).select()

然后在视图中:

{{for row in rows:}}

<div class="well">
    <table>
        <tr>
            <td>
             <div style="text-align:center">
<img width="200px"
     src="{{=URL('download', args=row.uploads.up_file)}}" />
</div>

            </td>
            <td><button>
            -
            </button></td><td><span class='votes'>{{=row.recipe.votes}}</span></td><td><button>
            +
            </button><td><strong>{{=A("comments",_href=URL('view_posts',args=row.recipe.id))}},{{=row.recipe.name}}</strong></td></td></tr>
    </table>

</div>
{{pass}}

注意,因为rows对象现在表示两个表之间的连接,所以必须同时使用表名和字段名来访问给定值(例如row.recipe.name而不是{{1 }})。为清楚起见,我在row.name循环中将for更改为recipe

相关问题