Turbogears-crud-operations

提供:Dev Guides
移動先:案内検索

TurboGears – CRUD操作

次のセッションメソッドはCRUD操作を実行します-

  • * DBSession.add(model object)*-レコードをマップされたテーブルに挿入します。
  • * DBSession.delete(model object)*-テーブルからレコードを削除します。
  • * DBSession.query(model).all()*-テーブルからすべてのレコードを取得します(SELECTクエリに対応)。

フィルター属性を使用して、取得したレコードセットにフィルターを適用できます。 たとえば、studentsテーブルでcity = 'Hyderabad’のレコードを取得するには、次のステートメントを使用します-

DBSession.query(model.student).filter_by(city = ’Hyderabad’).all()

ここで、コントローラーURLを介してモデルと対話する方法を確認します。

最初に、学生のデータを入力するためのToscaWidgetsフォームを設計しましょう

*Hello \ hello \ controllers.studentform.py*
import tw2.core as twc
import tw2.forms as twf

class StudentForm(twf.Form):
   class child(twf.TableLayout):
      name = twf.TextField(size = 20)
      city = twf.TextField()
      address = twf.TextArea("",rows = 5, cols = 30)
      pincode = twf.NumberField()

   action = '/save_record'
   submit = twf.SubmitButton(value = 'Submit')

RootController(Helloアプリケーションのroot.py)で、次の関数マッピング「/add」URLを追加します-

from hello.controllers.studentform import StudentForm

class RootController(BaseController):
   @expose('hello.templates.studentform')
   def add(self, *args, **kw):
      return dict(page='studentform', form = StudentForm)

次のHTMLコードを studentforml としてテンプレートフォルダーに保存します-

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:py = "http://genshi.edgewall.org/"
   lang = "en">

   <head>
      <title>Student Registration Form</title>
   </head>

   <body>
      <div id = "getting_started">
         ${form.display(value = dict(title = 'Enter data'))}
      </div>
   </body>

</html>

サーバーの起動後、ブラウザーに http://localhost:8080/add と入力します。 次の学生情報フォームがブラウザで開きます-

登録

上記のフォームは、 ’/save_record’ URLに送信されるように設計されています。 したがって、* save_record()関数を公開するには、 *root.py に追加する必要があります。 studentformからのデータは、この関数によって* dict()*オブジェクトとして受信されます。 学生モデルの基礎となる学生テーブルに新しいレコードを追加するために使用されます。

@expose()
#@validate(form = AdmissionForm, error_handler = index1)

def save_record(self, **kw):
   newstudent = student(name = kw['name'],city = kw['city'],
      address = kw['address'], pincode = kw['pincode'])
   DBSession.add(newstudent)
   flash(message = "new entry added successfully")
   redirect("/listrec")

追加に成功すると、ブラウザは ’/listrec’ URL にリダイレクトされます。 このURLは* listrec()関数*によって公開されます。 この関数は、studentテーブルのすべてのレコードを選択し、dictオブジェクトの形式でstudentlistlテンプレートに送信します。 この* listrec()*関数は次のとおりです-

@expose ("hello.templates.studentlist")
def listrec(self):
   entries = DBSession.query(student).all()
   return dict(entries = entries)

studentlistlテンプレートは、py:forディレクティブを使用して、entries辞書オブジェクトを反復処理します。 studentlistlテンプレートは次のとおりです-

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:py = "http://genshi.edgewall.org/">

   <head>
      <link rel = "stylesheet" type = "text/css" media = "screen"
         href = "${tg.url('/css/style.css')}"/>
      <title>Welcome to TurboGears</title>
   </head>

   <body>
      <h1>Welcome to TurboGears</h1>

      <py:with vars = "flash = tg.flash_obj.render('flash', use_js = False)">
         <div py:if = "flash" py:replace = "Markup(flash)"/>
      </py:with>

      <h2>Current Entries</h2>

      <table border = '1'>
         <thead>
            <tr>
               <th>Name</th>
               <th>City</th>
               <th>Address</th>
               <th>Pincode</th>
            </tr>
         </thead>

         <tbody>
            <py:for each = "entry in entries">
               <tr>
                  <td>${entry.name}</td>
                  <td>${entry.city}</td>
                  <td>${entry.address}</td>
                  <td>${entry.pincode}</td>
               </tr>
            </py:for>
         </tbody>

      </table>

   </body>
</html>

ここで http://localhost:8080/add に再度アクセスして、フォームにデータを入力します。 送信ボタンをクリックすると、ブラウザがstudentlistlに移動します。 また、「新しいレコードが正常に追加されました」というメッセージが点滅します。

エントリ