problem with list:reference

31 views
Skip to first unread message

P Page-McCaw

unread,
Jul 18, 2020, 8:46:53 PM7/18/20
to web2py-users
I am having trouble getting list:reference to work. I have made a tester app where db.py is:

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

db.define_table('product',
                 Field('name'),
                 Field('tags', 'list:reference tag'))

#this isn't necessary for the error, but things were getting out of hand
if db(db.product.id>0).count() != 0:
    db(db.tag.id > 0).delete()
    db(db.product.id > 1).delete()
    
a = db.tag.insert(name='red')
b = db.tag.insert(name='green')
c = db.tag.insert(name='blue')
db.product.insert(name='Toy Car', tags=[a, b, c])
db.product.insert(name='Toy Boat', tags=[a])

That part all seems to work and I get a correct database when I look in the Admin interface. This is from the manual. 
Then in the Database Administration interface, I create a new Product "Toy Truck" and select say "Green". But when I click submit, I get "Value not in database". If I try to add a new color to tag, the tag does not appear in the selection field when I then make a new product. I have similar problems in my own views, but figure if I can't get this...

villas

unread,
Jul 20, 2020, 8:55:50 AM7/20/20
to web2py-users
Your model deletes the records and recreates them every time the model runs.  This is not such a good idea for testing. 
Furthermore, it seems to retain the first product,  but deletes the referenced keys.
Your table ids are not reset to zero,  so your first product will probably have missing keys for tag.

Anyhow, here are two suggestions:
You can use truncate() rather than delete to empty the tables.
Only insert the test records when the database is empty.

So insert these lines under your table define statements.  Run model once and then comment out:
db.product.truncate()
db.tag.truncate()

Afterwards use the other code to recreate the records only once:
if db(db.product.id>0).count() == 0:
a = db.tag.insert(name='red')
b = db.tag.insert(name='green')
c = db.tag.insert(name='blue')
db.product.insert(name='Toy Car', tags=[a, b, c])
db.product.insert(name='Toy Boat', tags=[a])
Reply all
Reply to author
Forward
0 new messages