On Wednesday, November 15, 2017 at 9:46:34 AM UTC-5, Maurice Waka wrote:
>
> *controller*
> @auth.requires_login()
> def view_searches():
>     form = SQLFORM(Post)
>     if form.process().accepted:
>         #pass
>         response.flash = 'done'
>     if request.vars.message:
>         db.post.insert(message = request.vars.message)
>         db.commit()
>

First, by default, form.process() will itself insert a record in the 
database, so you should not subsequently do this manual insert, as you will 
get two copies of the same data in the database. Second, there is no reason 
to call db.commit() here -- the entire request is wrapped in a transaction, 
and any inserts made within the transaction will be immediately visible to 
subsequent queries within the same request. The danger of calling 
db.commit() is that if there is a subsequent error in the request handling, 
the insert will not be rolled back by the framework.
 

>     quiz = db(db.post.author == auth.user.id).select(db.post.ALL, 
> limitby=(1,0))
>

What records do you want in quiz? limitby=(1, 0) will actually give you all 
but the first record (and because you don't specify an orderby, the exact 
order of records isn't even guaranteed). If you want the latest record, do 
something like:

quiz = db(db.post.author == auth.user.id).select(db.post.ALL, orderby=~db.
post.created_on, limitby=(0, 1))

The does a descending sort on created_on and then selects the first record, 
which will be the most recently created.
 

> def Search_name():
>   db = current.db
>   auth = Auth(db, hmac_key=Auth.get_or_create_key())
>   auth.define_tables()
>

I assume this function is in a module and imported into a controller or 
model in the app. If so, there is no reason to redefine auth and its 
tables. Simple add auth to the current object, or even better, pass the 
auth object to this function directly.
 

>   name  = [r.message for r in db(db.post.author == auth.user.id
> ).select(db.post.ALL)][-1]
>

The above is an inefficient way to get the last message, as you are 
unnecessarily retrieving all the records from the database, then iterating 
through all of them, and only then selecting the last one. Instead, use the 
code shown above to get only the most recent record.

Anthony

-- 
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to web2py+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to