レコードの表現

□未翻訳

□翻訳中

■翻訳完了(細田謙二)

■レビュー(Omi Chiba)

レコードの表現

これは省略可能ですが、レコードの書式表現を指定するのに推奨されます:

It is optional but recommended to specify a format representation for records:

1.

>>> db.define_table('person', Field('name'), format='%(name)s')

または

or

1.

>>> db.define_table('person', Field('name'), format='%(name)s %(id)s')

より複雑なものは関数を用いて次のように書きます:

or even more complex ones using a function:

1.

2.

>>> db.define_table('person', Field('name'),

format=lambda r: r.name or 'anonymous')

format属性は、2つの目的のために使用されます:

The format attribute will be used for two purposes:

  • セレクト/オプションのドロップダウンにおいて、参照先のレコードを表現するためです。

  • To represent referenced records in select/option drop-downs.

  • このテーブルを参照するすべてのフィールドに対して、db.othertable.person.represent属性を設定するためです。これは、SQLTABLEがidによって参照を表示するのではなく、代わりに好ましい書式表現を用いることを意味します。

  • To set the db.othertable.person.represent attribute for all fields referencing this table. This means that SQLTABLE will not show references by id but will use the format preferred representation instead.

以下に示すのはFieldコンストラクタのデフォルトの値です:

These are the default values of a Field constructor:

1.

2.

3.

4.

5.

6.

7.

8.

Field(name, 'string', length=None, default=None,

required=False, requires='<default>',

ondelete='CASCADE', notnull=False, unique=False,

uploadfield=True, widget=None, label=None, comment=None,

writable=True, readable=True, update=None, authorize=None,

autodelete=False, represent=None, compute=None,

uploadfolder=os.path.join(request.folder,'uploads'),

uploadseparate=None)

す べてのものが各フィールドに関連しているというわけではありません。"length"は、"string"型のフィールドに対してのみ関連していま す。"uploadfield"と"authorize"は、"upload"型のフィールドに対してのみ関連しています。"ondelete" は"reference"と"upload"型のフィールドに対してにみ関連しています。

Not all of them are relevant for every field. "length" is relevant only for fields of type "string". "uploadfield" and "authorize" are relevant only for fields of type "upload". "ondelete" is relevant only for fields of type "reference" and "upload".

  • length は"string"や、"password"、"upload"フィールドの最大長を設定します。lengthが指定されていない場合は、デフォルト値が使用されます。ただし、デフォルト値に関しては後方互換は保証されていません。意図しないマイグレーションやアップグレードを避けるため、string、password、uploadフィールドに対して、常にlengthを指定することを推奨します。

  • sets the maximum length of a "string", "password" or "upload" field. If length is not specified a default value is used but the default value is not guaranteed to be backward compatible. To avoid unwanted migrations on upgrades, we recommend that you always specify the length for string, password and upload fields.

  • default はフィールドのデフォルト値を設定します。デフォルト値は値が明示的に指定されていない場合において挿入を実行したときに使用されます。また、SQLFORMを用いたテーブルによって構築されたフォームを前もって入力するために使用されます。

  • sets the default value for the field. The default value is used when performing an insert if a value is not explicitly specified. It is also used to pre-populate forms built from the table using SQLFORM.

  • required はDALに、このフィールドの値が明示的に指定されていない場合、挿入することを許さないようにします。

  • tells the DAL that no insert should be allowed on this table if a value for this field is not explicitly specified.

  • requires はバリデータ、または、バリデータのリストです。これは、DALによっては使用されず、SQLFORMによって使用されます。以下に、与えられた型に対するデフォルトのバリデータの一覧を示します:

  • is a validator or a list of validators. This is not used by the DAL, but it is used by SQLFORM. The default validators for the given types are shown in the following table:

Decimalは、Pythonのdecimalモジュールに定義されているような、Decimalオブジェクトを要求し、返します。SQLiteではdecimal型は処理されないので、doubleとして扱われます。(n、m)はそれぞれ、合計の桁数と小数点以下の桁数です。

Decimal requires and returns values as Decimal objects, as defined in the Python decimalmodule. SQLite does not handle the decimal type so internally we treat it as a double. The (n,m) are the number of digits in total and the number of digits after the decimal point respectively.

list: フィールドは特殊です。なぜなら、NoSQL上の特定の非正規化の特徴(Google App Engineでは、ListPropertyやStringListPropertyといったフィールド型)に対して有利になるように、そして、それらを 他のサポートされたリレーショナル・データベースに移植できるように設計されているからです。リレーショナルデータベースでは、そのリストはtextフィールドとして保存されます。項目は、|によって区切られ、文字列項目の各|は||にエスケープされます。詳細は、それ自体を扱う節において説明されています。

The list: fields are special because they are designed to take advantage of certain denormalization features on NoSQL (in the case of Google App Engine, the field typesListProperty and StringListProperty) and back-port them all the other supported relational databases. On relational databases lists are stored as a text field. The items are separated by a| and each | in string item is escaped as a ||. They are discussed in their own section.

requires=...は、フォーム・レベルで強制され、required=TrueはDAL(挿入)レベルで強制されることに注意してください。一方、not nullやunique、ondeleteはデータベース・レベルで強制されます。それらは時として冗長に見えるかもしれませんが、DALを用いたプログラミングにおいて、その区別を維持することは重要です。

Notice that requires=... is enforced at the level of forms, required=True is enforced at the level of the DAL (insert), while notnull, unique and ondeleteare enforced at the level of the database. While they sometimes may seem redundant, it is important to maintain the distinction when programming with the DAL.

  • ondelete は"ON DELETE"SQL文へと変換されます。デフォルトでは、"CASCADE"に設定されています。これは、レコードを削除するときに、それを参照しているすべてのレコードを削除するようにデータベースに指示します。この機能を無効にするには、ondeleteを"NO ACTION"に設定してください。

  • translates into the "ON DELETE" SQL statement. By default it is set to "CASCADE". This tells the database that when it deletes a record, it should also delete all records that refer to it. To disable this feature, set ondelete to "NO ACTION".

  • notnull=True は"NOT NULL"SQL文へと変換されます。これにより、データベースから、このフィールドにnull値が挿入されることを防ぎます。

  • translates into the "NOT NULL" SQL statement. It prevents the database from inserting null values for the field.

  • unique=True は"UNIQUE"SQL文へと変換され、フィールドの値が、そのテーブル内でユニークであることを保証します。これはデータベース・レベルで強制されます。

  • translates into the "UNIQUE" SQL statement and it makes sure that values of this field are unique within the table. It is enforced at the database level.

  • uploadfield は"upload"型のフィールドに対してのみ適用されます。"upload"型のフィールドはどこかに保存されたファイル、デフォルトではアプリケーションの"uploads/"フォルダ以下のファイルシステム上に保存されたファイルの名前を格納します。uploadfield設定されている場合、ファイルは同じテーブルのblobフィールドに格納され、uploadfieldの値はそのblobフィールドの名前になります。この点に関してはSQLFORMのコンテキストでより詳しく後述します。

  • applies only to fields of type "upload". A field of type "upload" stores the name of a file saved somewhere else, by default on the filesystem under the application "uploads/" folder. If uploadfield is set, then the file is stored in a blob field within the same table and the value of uploadfield is the name of the blob field. This will be discussed in more detail later in the context of SQLFORM.

  • uploadfolder はデフォルトではアプリケーションの"uploads/"フォルダに成ります。別のパスが設定されている場合、ファイルは別のフォルダにアップロードされます。たとえば、uploadfolder=os.path.join(request.folder,'static/temp')とすると、ファイルはweb2py/applications/myapp/static/tempフォルダにアップロードされます。

  • defaults to the application's "uploads/" folder. If set to a different path, files will uploaded to a different folder. For example, uploadfolder=os.path.join(request.folder,'static/temp') will upload files to the web2py/applications/myapp/static/temp folder.

  • uploadseparate は、Trueに設定されていると、ファイルはuploadfolderフォルダの異なるサブフォルダの下にアップロードされます。これは、非常に多くのファイルを同じフォルダ/サブフォルダに置くことを回避するために最適化されています。注意:システムの中断なしに、uploadseparateの値をTrueからFalseに変更することはできません。web2pyは分解したサブフォルダを使用するかしないかのどちらかしかとることはできません。ファイルをアップロードしてからこの挙動を変更すると、web2pyはそれらのファイルを取り出すことができなくなります。これが起こった場合は、ファイルを移動し、問題を解決することは可能ですが、ここでは説明しません。

  • if set to True will upload files under different subfolders of theuploadfolder folder. This is optimized to avoid too many files under the same folder/subfolder. ATTENTION: You cannot change the value of uploadseparate from True to False without breaking the system. web2py either uses the separate subfolders or it does not. Changing the behavior after files have been uploaded will prevent web2py from being able to retrieve those files. If this happens it is possible to move files and fix the problem but this is not described here.

  • widget は、利用可能なウィジェット・オブジェクトの1つである必要があります。カスタム・ウィジェットやSQLFORM.widgets.string.widgetなどです。利用可能なウィジェットのリストは後述します。各フィールドの型は、デフォルトのウィジェットを持ちます。

  • must be one of the available widget objects, including custom widgets, for example: SQLFORM.widgets.string.widget. A list of available widgets will be discussed later. Each field type has a default widget.

  • label は自動生成されるフォームにおいてこのフィールドにたいして使用されるラベルを保持する文字列(または文字列にシリアライズできるもの)です。

  • is a string (or something that can be serialized to a string) that contains the label to be used for this field in autogenerated forms.

  • comment は、このフィールドに関連付けられたコメントを保持し、自動生成されるフォームにおいて入力フィールドの右側に表示される文字列(または文字列にシリアライズできるもの)です。

  • is a string (or something that can be serialized to a string) that contains a comment associated with this field, and will be displayed to the right of the input field in the autogenerated forms.

  • writable もしフィールドがwritableだと、自動生成される作成と更新フォームにおいて編集可能になります。

  • if a field is writable, it can be edited in autogenerated create and update forms.

  • readable もしフィールドがreadableだと、読み取り専用フォームにおいて表示されます。もしフィールドがreadableでもwritableでもない場合、作成と更新フォームにおいてフィールドは表示されません。

  • if a field is readable, it will be visible in readonly forms. If a field is neither readable nor writable, it will not be displayed in create and update forms.

  • update は、レコードが更新された時における、このフィールドに対するデフォルト値になります。

  • contains the default value for this field when the record is updated.

  • compute は、オプション的な関数です。レコードが挿入、または、更新されたとき、compute関数が実行され、フィールドにはその関数の戻り値が入力されます。レコードはcompute関数にdictとして渡されます。そのdictには、そのフィールドの現在の値や、他のどのcomputeフィールドの値も含まれていません。

  • is an optional function. If a record is inserted or updated, the compute function will be executed and the field will be populated with the function result. The record is passed to the compute function as a dict, and the dict will not include the current value of that, or any other compute field.

  • authorize は、"upload"フィールドのみにおいて、対応するフィールドのアクセスコントロールに必要です。詳細は、認証と承認の文脈において後述します。

  • can be used to require access control on the corresponding field, for "upload" fields only. It will be discussed more in detail in the context of Authentication and Authorization.

  • autodelete は、アップロードされたファイルを参照するレコードが削除されたときに、対応するファイルが削除されるかどうかを決めます。"upload"フィールドに対してのみです。

  • determines if the corresponding uploaded file should be deleted when the record referencing the file is deleted. For "upload" fields only.

  • represent は、None、または、フィールド値を受け取りそのフィールド値に対する別の表現を返す関数への参照をとります。例:

  • can be None or can point to a function that takes a field value and returns an alternate representation for the field value. Examples:

1.

2.

3.

4.

db.mytable.name.represent = lambda name: name.capitalize()

db.mytable.other_id.represent = lambda id: db.other(id).myfield

db.mytable.some_uploadfield.represent = lambda value: \

A('get it', _href=URL('download', args=value))

"blob"フィールドもまた特別です。デフォルトでは、バイナリデータは、実際のデータベースフィールドに保存される前に、base64でエンコードされ、抽出時にデコードされます。これには、blobフィールドに必要なものより25%余分に記憶領域を使用するというマイナスの効果がありますが、2つの利点があります。平均的には、web2pyとデータベースサーバー間のデータ通信量を削減します。そして、通信をバックエンド固有のエスケープ規則から独立させます。

"blob" fields are also special. By default, binary data is encoded in base64 before being stored into the actual database field, and it is decoded when extracted. This has the negative effect of using 25% more storage space than necessary in blob fields, but has two advantages. On average it reduces the amount of data communicated between web2py and the database server, and it makes the communication independent of back-end-specific escaping conventions.

既存のテーブルに関してデータベースに問い合わせることができます:

You can query the database for existing tables:

1.

2.

>>> print db.tables

['person']

既存のフィールドに関してもテーブルに問い合わせることができます:

You can also query a table for existing fields:

1.

2.

>>> print db.person.fields

['id', 'name']

"id"というフィールドは宣言しないでください。web2pyは、何かしらの方法で、それを作成するからです。すべてのテーブルは、"id"というフィールドをデフォルトで持っています。これは、(1から始まる)自動インクリメントした整数のフィールドで、相互参照や、各レコードをユニークにするために用いられます。すなわち、"id"はプライマリーキーです。(注:idが1から始まるかはバックエンドによります。たとえばこれは、Google App Engine(GAE)では適用されません。)

Do not declare a field called "id", because one is created by web2py anyway. Every table has a field called "id" by default. It is an auto-increment integer field (starting at 1) used for cross-reference and for making every record unique, so "id" is a primary key. (Note: the id's starting at 1 is back-end specific. For example, this does not apply to the Google App Engine (GAE).)

オプション的に、type='id'とするフィールドを定義することができます。web2pyはこのフィールドを自動インクリメントしたidフィールドとして使用します。これは、レガシーなデータベーステーブルにアクセスするとき以外には推奨されません。いくつかの制約がありますが、複数の異なるプライマリキーを使用することもできます。これについては、"レガシー・データベースとキー付きテーブル"の節で後述します。

Optionally you can define a field of type='id' and web2py will use this field as auto-increment id field. This is not recommended except when accessing legacy database tables. With some limitation, you can also use different primary keys and this is discussed in the section on "Legacy databases and keyed tables".

テーブルの型を問い合わせることができます:

You can query for the type of a table:

1.

2.

>>> print type(db.person)

<class 'gluon.sql.Table'>

また、DAL接続から、次のようにして、そのテーブルにアクセスすることができます:

and you can access a table from the DAL connection using:

1.

2.

>>> print type(db['person'])

<class 'gluon.sql.Table'>

同様に、フィールドの名前から、複数の同等な方法でフィールドにアクセスすることができます:

Similarly you can access fields from their name in multiple equivalent ways:

1.

2.

3.

4.

5.

6.

>>> print type(db.person.name)

<class 'gluon.sql.Field'>

>>> print type(db.person['name'])

<class 'gluon.sql.Field'>

>>> print type(db['person']['name'])

<class 'gluon.sql.Field'>

フィールドが与えられたら、その定義に設定されている属性にアクセスすることができます:

Given a field, you can access the attributes set in its definition:

1.

2.

3.

4.

5.

6.

7.

8.

>>> print db.person.name.type

string

>>> print db.person.name.unique

False

>>> print db.person.name.notnull

False

>>> print db.person.name.length

32

親のテーブルやテーブル名、親の接続にもアクセスできます:

including its parent table, tablename, and parent connection:

1.

2.

3.

4.

5.

6.

>>> db.person.name._table == db.person

True

>>> db.person.name._tablename == 'person'

True

>>> db.person.name._db == db

True