2016-03-21 92 views
0

我想從web2py的視圖中查詢數據庫表,因爲我需要從當前表中的每一行的另一個表中獲取一個字段,所以我寫了這樣的代碼:從視圖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

可以做到這一點,但它是不是很有效,因爲你會爲表中的每一行一個單獨的查詢。相反,查詢控制器創建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循環中,我將recipe更改爲row