update_or_insert

31 views
Skip to first unread message

Mirek Zvolský

unread,
May 2, 2016, 6:13:07 AM5/2/16
to web2py-users
I have 'many:many' table relationship:    base =< join >= index

I need to be sure that I have some value in 'index', if no, then add them there.
And I need to know its ID, because in last step I will add both ID's (from 'index' and from 'base') to the 'join' table.

It is not very plesant for me that db.index.update_or_insert()
- will return ID in case of insert,
- but will return None if the row exists already.

I think this is behaviour by design.
However can I get the ID of existing row somewhere after the .update_or_insert() ?
Or what should I use instead of .update_or_insert() ?
I need very fast record lookup, because I need run the cycle with ~3000 tests in 'index' table

Thanks...

Limedrop

unread,
May 2, 2016, 8:08:59 PM5/2/16
to web2py-users
It looks like update_or_insert() will always do two database hits and, as you say, even then doesn't give you the id of the existing record.  It goes something like this (pseudo code for clarity):

record = db.table.select()
if record:
    update_record()
else:
   insert record()

So it's a simple function that you could easily substitute with your own code.  However if you want to reduce database hits, I guess you could use try/except instead.
Is it more likely that the record will exist or not exist?  Do the most likely thing.  And then if that fails, and only then, do the second query.  This assumes that the appropriate fields in the index table have been defined with unique=True.
Reply all
Reply to author
Forward
0 new messages