On Jul 20, 9:40 am, bloeper <[email protected]> wrote:
> Hi all,
>
> I have a question, i am creating an blog application.
> The blog model is as follow:
> class Blog( DeclarativeBase ):
>     __tablename__ = 'blog'
>
>     id = Column( Integer, primary_key = True )
>     title = Column( Unicode( 100 ), nullable = False )
>     slug = Column( Unicode( 110), nullable = False, unique = True )
>     date = Column( DateTime, nullable = False )
>     content = Column( Text, nullable = False )
>     reaction = Column( Integer, nullable = True )
>     author = Column( Integer, ForeignKey( 'tg_user.user_id',
> onupdate="CASCADE", ondelete="CASCADE" ) )
>
>     def __init__( self, title, content, reaction, author, tags ):
>       self.title = title
>       self.slug = urlify( title )
>       self.date = datetime.now()
>       self.content = content
>       self.reaction = reaction
>       self.author = author
>
> Now is the question (when I retrieve the information) through:
> @expose('nextrus.templates.new.blog')
>     def blog( self, slug = 'first-post'):
>       try:
>         blog = DBSession.query( Blog ).filter_by( slug = slug ).one()
>       except NoResultFound:
>         blog = DBSession.query( Page ).filter_by( slug = u'not-
> found').one()
>
>       try:
>         menus = DBSession.query( Menu ).order_by( Menu.order )
>       except NoResultFound:
>         pass
>
>       return dict( blog = blog, menus = menus )
>
> How can i get the username from the table of tg_users?
> I know it's quite simple but can't find it in the tg documentation.
>
> Thanks in advance.
>
> Greetings,
>
> Bloeper


Hey Bloeper,

you need to create the relationship first on your model

from sqlachemy.orm import relation
from package.model import User

class Blog( DeclarativeBase ):
    __tablename__ = 'blog'
    id = Column( Integer, primary_key = True )
    title = Column( Unicode( 100 ), nullable = False )
    slug = Column( Unicode( 110), nullable = False, unique = True )
    date = Column( DateTime, nullable = False )
    content = Column( Text, nullable = False )
    reaction = Column( Integer, nullable = True )

     # create a relationship
    author_id = Column( Integer, ForeignKey( 'tg_user.user_id',
onupdate="CASCADE", ondelete="CASCADE" ) )
    author = relation(User, backref='blogs', uselist=False) #NOTE the
uselist ensures only one author and dont return a list

now in you can access the author in your template or controller via
the relationship

blog.author.name_variable

More info can be found in the SQLAlchemy docs:
http://www.sqlalchemy.org/docs/05/reference/orm/mapping.html?highlight=relation#sqlalchemy.orm.relation

-- 
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en.

Reply via email to