tejzpr
tejzpr

Reputation: 995

Web2py Foreign key ID getting displayed

I am using web2py for the first time for a project. I made a field in the following way

db.define_table('my_years',Field('case_year',db.case_years,required=True,requires = IS_IN_DB( db, 'case_years.id', '%(year)s' )));

This field is referring to another table which has a list of years, that table is defined as follows:

db.define_table('case_years',Field('year'),format = '%(year)s') ;

Then I am displaying the my_years in a view.

<table id="case_list">
    <thead>
        <tr>
            <th>Number</th>
            <th>Year</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
            {{ for case in cases: }}
            <tr>
                <td>{{=case.case_number}}</td>
                <td>{{=case.case_year}}</td>
                <td><a href= "{{=URL(r=request, f='edit', args=case.id)}}"> Edit Case </a></td>
            </tr>
            {{pass}}
    </tbody>
</table>

The issue I am facing is that while displaying the year from "my_years" I'm seeing the primary key ID of the case_years instead of seeing the Value (i.e. case_years.year) in years.

Please help..

Upvotes: 0

Views: 1259

Answers (1)

Anthony
Anthony

Reputation: 25536

If you remove the explicit requires argument, then you will get a default requires that is the same as you defined it, plus you will get a default represent attribute that will display the year instead of the id in SQLTABLE, SQLFORM.grid, and read and update SQLFORM's.

Field('case_year', db.case_years, required=True)

Alternatively, you could explicitly define the represent attribute:

Field('case_year', db.case_years, required=True,
      requires=IS_IN_DB(db, 'case_years.id', '%(year)s'),
      represent=lambda id, r: db.case_years(id).year))

Also, note that you don't need semicolons at the ends of your lines of code.

UPDATE (based on new code provided):

In your view, the field's represent attribute will have no effect because you are not using a SQLFORM or SQLTABLE but simply displaying a single value:

{{=case.case_year}}

case.case_year is an id value, so that's what will get displayed above. If you want to display the associated year from the db.case_years table, you need to do:

{{=db.case_years(case.case_year).year}}

You can also do a recursive select:

{{=case.case_year.year}}

which is equivalent to the above. Note, both methods will result in an additional database query for each case, so this will be somewhat inefficient. Instead, you can make your initial query for the cases a join and include the "year" field from the case_years table (see http://web2py.com/books/default/chapter/29/06#Inner-joins).

Upvotes: 2

Related Questions