> Hi,
>
> I am having trouble using DAL the web2py way. I am trying to create a
> personal website so I can post articles. I have all my articles for
> different subjects stored in a single table with a field "main_tag",
> which tells the subject of the article. I will display them on the
> webpage in different pages, organized by subject.
>
> # ==============================================#
> db = DAL('sqlite://storage.sqlite')
>
> db.define_table('articles',
>   Field('title', 'string'),
>   Field('body', 'text'),
>   Field('main_tag', 'string'),
>   Field('sec_tag', 'string'))
>
> db.articles.title.requires = IS_NOT_IN_DB(db, db.articles.title)
> db.articles.body.requires = IS_NOT_EMPTY()
> db.articles.main_tag.requires = IS_NOT_EMPTY()
> # ==============================================#
>
> How do I write the command below the web2py way, instead of using
> executesql()?
>
> # Selects articles by subject ("main_tag" field)
> # request.args() used in the view files
> def articles():
>   title = db.executesql('SELECT title FROM articles WHERE id=%s AND
> main_tag=%s' % (request.args(0), request.args(1)))
>    body = db.executesql('SELECT body FROM articles WHERE id=%s AND
> main_tag=%s' % (request.args(0), request.args(1)))
>    return dict(title=title, body=body)
>

Testing in my console:

In [13]: db.articles.insert(title='foobar')
1
in [14]: db.commit()
In [15]: title = db(db.articles.id==1).select(db.articles.title).first()
In [16]: print title
-------> print(title)
<Row {'title':'foobar'}>

Or

In [20]: title =
db(db.articles.id==1).select(db.articles.title).first()['title']

In [21]: print title
-------> print(title)
foobar

You can use the index instead of first()

In [20]: title = db(db.articles.id==1).select(db.articles.title)[0]['title']

In [21]: print title
-------> print(title)
foobar

And the short way:

In [26]: title = db.articles[1]['title']
In [27]: print title
-------> print(title)
foobar


>
So in your case, you can do:

def articles():
    if request.args:
        query = (db.articles.id
==request.args[0])&(db.articles.main_tag==request.args[1])
    else:
        query = db.articles.id>0

    #using first() / last()
    title = db(query).select(db.articles.title).first()['title']
    body = db(query).select(db.articles.body).first()['body']

    #using index [0] [1] [2] ......
    title = db(query).select(db.articles.title).first[0]['title']
    body = db(query).select(db.articles.body)[0]['body']

    return dict(title=title, body=body)


But, remember, this is just the ways I've found, I think Massimo has a
better magic to do it.
Running your app from console/terminal is the better way to test DAl queries





Thanks,
>
> Eduardo
>
>

Bruno
-- 

http://rochacbruno.com.br

Reply via email to