如何使用turbogears和sqlalchemy以多对多关系保存数据

发布于 2024-08-18 18:08:14 字数 2226 浏览 7 评论 0原文

您好,我在用户和组之间有多对多的关系。我想在我的数据库中添加一个具有多个组的用户。如果我的数据库如下,我该怎么做,

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)

但是这样做会给我一个错误

@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")

请帮我解决这个问题。提前致谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

网白 2024-08-25 18:08:14

我相信答案就在您未在问题中发布的错误消息中。 user.groups 是一个 Group 对象的列表,同时您将从表单中获取的字符串列表(?)分配给它。我还看到没有明确的 DBSession.commit() 调用。您确定 TurboGears 会为您做到吗?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文