Do not do dal queries in a try..except. If the db query fails it may not be 
automatically rolled back.
I think you want:

category = request.args(0) and db.blog_cat(slug=request.args(0))
query = db.blog_post.blog_cat.contains(category.id) if category else 
db.plog_post
posts = db(query).select(orderby=~db.blog_post.created_on)

Now notice that this works db.blog_post.blog_cat.contains(category.id)
and it may be fine for a small number of posts but for many posts you may 
want to use a link table to implement many2many.


On Saturday, 12 July 2014 05:04:45 UTC-5, Ruud Schroen wrote:
>
> Hi group!
>
> I'm building a small blog where the user has the ability to assign 
> multiple categories to blog posts.
> My quesition is.. what is the proper way to query those posts?
>
> db.define_table('blog_cat',
>                 Field('name', 'string', label=T('Name of the category')),
>                 Field('slug', compute=lambda r: IS_SLUG()(r['name'])[0]),
>                 Field('description', 'string', label=T('Describe what will 
> be inside this category'))
>                 )
>
> db.define_table('blog_post',
>                 Field('blog_cat', 'list:reference blog_cat', 
> requires=IS_IN_DB(db,db.blog_cat.id,'%(name)s', multiple=True), 
> label=T('Chose one or more categories')),
>                 Field('title', 'string', label=T('Name the title of your 
> post')),
>                 Field('body', 'text', label=T('Your post'), 
> widget=ckeditor.widget),
>                 auth.signature
>                 )
>
> I created two categories and two posts. One post only has one category 
> while the other has two.
>
> This is my query:
>
> try:
>     category = db(db.blog_cat.slug==request.args(0)).select().first().id
>     posts = db(db.blog_post.blog_cat == 
> category).select(orderby=~db.blog_post.created_on)
> except:
>     posts = db(db.blog_post.id>0).select(orderby=~db.blog_post.created_on)
>
> The problem is when a post has multiple categories, it is not shown. How 
> do I solve this?
>

-- 
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