views:

62

answers:

1

hi i have a many to many relationship between a user and a group.and i will like to add a user with many groups in my database.how do i do that if my database is as follows

user_group_table = Table('tg_user_group', metadata,
    Column('user_id', Integer, ForeignKey('tg_user.user_id',
        onupdate="CASCADE", ondelete="CASCADE")),
    Column('group_id', Integer, ForeignKey('tg_group.group_id',
        onupdate="CASCADE", ondelete="CASCADE"))
)

class Group(DeclarativeBase):
    """
    Group definition for :mod:`repoze.what`.1

    Only the ``group_name`` column is required by :mod:`repoze.what`.

    """

    __tablename__ = 'tg_group'

    #{ Columns

    group_id = Column(Integer, autoincrement=True, primary_key=True)

    group_name = Column(Unicode(16), unique=True, nullable=False)

    display_name = Column(Unicode(255))

    created = Column(DateTime, default=datetime.now)

    #{ Relations

    users = relation('User', secondary=user_group_table, backref='groups')

    #{ Special methods

    def __repr__(self):
        return '<Group: name=%s>' % self.group_name

    def __unicode__(self):
        return self.group_name

    #}
class User(DeclarativeBase):
    """
    User definition.

    This is the user definition used by :mod:`repoze.who`, which requires at
    least the ``user_name`` column.

    """
    __tablename__ = 'tg_user'

    #{ Columns

    user_id = Column(Integer, autoincrement=True, primary_key=True)

    user_name = Column(Unicode(16), unique=True, nullable=False)

    email_address = Column(Unicode(255), unique=True, nullable=False,
                           info={'rum': {'field':'Email'}})

    display_name = Column(Unicode(255))

    _password = Column('password', Unicode(80),
                       info={'rum': {'field':'Password'}})

    created = Column(DateTime, default=datetime.now)

doing it this way however gives me an error

@expose()
def  user_save(self, **kw):

    user = User()   
    user.user_name = kw['user_name']
    user.display_name = kw['display_name']
    user.email_address = kw['Email']
    user._password = kw['password']

    user.groups.extend(kw['groups'])



    DBSession.add(user)
    DBSession.flush()
    flash("successfully saved...")


    flash(user)
    redirect("/user_new")

pls help me solve this.thanks in advance

A: 

I believe the answer is in the error message that you havn't posted in the question. user.groups is a list of Group objects, while you assign a list of strings(?) got from form to it. Also I see no explicit DBSession.commit() call. Are you sure TurboGears will do it for you?

Denis Otkidach

related questions