8

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

What does this format do here?

Jensen
  • 1,653
  • 4
  • 26
  • 42

1 Answers1

11

The format argument is used to determine how fields in other tables that reference the 'person' table will be displayed. For example, if you define:

db.define_table('dog',
    Field('name'),
    Field('owner', db.person)

The 'owner' field is a reference field that references the 'person' table (i.e., it stores record id's of records from the 'person' table). In most cases, when you display data from the 'dog' table, you don't want to display the raw db.person record id that is stored in the 'owner' field because that doesn't have any meaning -- instead, it makes more sense to display the 'name' of the person. In web2py, the format attribute of the table enables this automatic substitution in both forms and tables.

When you create a SQLFORM based on the 'dog' table, it will automatically generate a drop-down list for the 'owner' field, and because of the format='%(name)s' argument to the 'person' table definition, the drop-down list will display db.person names instead of record id's (even though upon form submission, the 'owner' field will store the associated record id rather than the name).

Also, if you display records from the 'dog' table in a SQLTABLE or SQLFORM.grid, the 'owner' field will show the owner's name rather than the owner's record id.

See http://web2py.com/books/default/chapter/29/6#Record-representation.

Anthony
  • 25,466
  • 3
  • 28
  • 57
  • Thanks. What I don't understand here is what do this symbol **%** and the **s** at the end of argument mean – Jensen Jan 05 '12 at 20:12
  • That's just standard [Python string formatting notation](http://docs.python.org/library/stdtypes.html#string-formatting-operations). The `format` string can include the names of any fields within the table. – Anthony Jan 05 '12 at 20:46
  • By the way, how to get the username of a user who has already logged in my website on server-side? Thank you – Jensen Jan 05 '12 at 23:42
  • I've figured it out. Using **session.auth.user.username**, right? – Jensen Jan 06 '12 at 00:04
  • Yes, though you can also get it from `auth.user.username`. – Anthony Jan 06 '12 at 04:32
  • Thank you Anthony, A small clarification please, does `format='%(name)s` mean that the primary key is now the field 'name' instead of 'id' in the persons table? – Josyula Krishna Aug 14 '13 at 10:55
  • No, the `format` argument is used purely for display purposes -- it does not affect the underlying data or primary key in any way. – Anthony Aug 14 '13 at 15:36