0

我正在尝试从 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 的新手

4

1 回答 1

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而不是row.name)。为了清楚起见,在for循环中,我更改reciperow.

于 2016-03-21T17:26:56.453 回答