how to making a field unique based on another field's value

22 views
Skip to first unread message

KRG KCIHTRAK

unread,
Jun 25, 2014, 11:17:17 AM6/25/14
to web...@googlegroups.com
I have two tables like below.
Table1 (Field(name), unique = True)
Table2 (Field(table1_name, 'reference Table1',
           Field(name))

I want to make the Table2's name field as unique based on the value in table1_name.

how can I do it with web2py?

Ian W. Scott

unread,
Jun 25, 2014, 12:08:14 PM6/25/14
to web...@googlegroups.com
I believe you just set this through the "requires" property of the field:

db.table2.table1_name.requires(IS_IN_DB(db, 'table1.name',
                                        db
.table1._format))

That prevents entering any values in table1_name that aren't in table1.name. I believe you can also set unique=True on table2.table1_name (just as you have on table1.name). Then the values will be unique within table2.table1_name and will also be drawn from table1.name.

Massimo Di Pierro

unread,
Jun 25, 2014, 12:44:40 PM6/25/14
to web...@googlegroups.com
It is not too simple. Given:

db.define_table('table1', Field('name'))
db.define_table('table2',Field('name'),Field(table1','reference table1'))

define:

def require_unique(form):
      if db.table2(name=form.vars.name,table1=form.vars.table1): form.errors.name="Must be unique!"

then when processing forms apply the above check:

form = SQLFORM(db.table2)
form.process(onvalidation=require_unique)
Reply all
Reply to author
Forward
0 new messages