TurboGears2/SQLAlchemy:将新行插入到具有自动增量主键的表中

发布于 2024-08-03 19:39:14 字数 819 浏览 10 评论 0原文

我是一名菜鸟,正在尝试了解 TG2 和 SQLAlchemy。我目前正在解决的具体问题是当 PK 字段配置为自动增量时如何将新行插入表中。

例如:

在我的 myproject.model.myproject.py 文件中,我定义了下表:

class Dj(DeclarativeBase):
    __tablename__ = 'djs'

    #{ Columns

    djID = Column(Integer,  autoincrement=True, primary_key=True)
    djname = Column(String)
    djwebpage = Column(String)
    #}

在我的 websetup.py 文件中,我用一些初始数据填充它。由于这是第一行数据,我作弊并将 djID 定义为“1”。

dj = model.Dj("1", "DJ Anonymous", "http://www.djanonymous.com")

如果我希望 websetup.py 在 djs 表中创建第二行(通过对象 Dj),我该怎么做?

我之前尝试过很多不同的事情,但都没有成功。例如,如果我使用相同的格式,但只包含 2 个字符串(对于 djname 和 djwebpage 列),我会收到一条错误消息,抱怨我没有提供足够的参数。

当然,最终,我需要弄清楚如何创建一个控制器,以允许我将新条目插入表中......但我会一次学习一步,并且很感激能够成功地预填充通过 websetup.py 文件包含多行的表。希望这能给我线索,让我能够进入下一步。

提前致谢!

I am a noob and am trying to get my head around TG2 and SQLAlchemy. The specific problem I am wrestling with at the moment is how to insert a new row into a table when the PK field is configured as autoincrement.

For example:

in my myproject.model.myproject.py file I defined the following table:

class Dj(DeclarativeBase):
    __tablename__ = 'djs'

    #{ Columns

    djID = Column(Integer,  autoincrement=True, primary_key=True)
    djname = Column(String)
    djwebpage = Column(String)
    #}

In my websetup.py file I populate it with some initial data. Since this is the first row of data, I cheated and just defined the djID to be "1"

dj = model.Dj("1", "DJ Anonymous", "http://www.djanonymous.com")

If I wanted the websetup.py to create a second row in the djs table (via object Dj) how would I do that?

I previously tried a number of different things and have had no luck. For example If I used the same format but did only included 2 strings (for the djname and djwebpage columns) I get an error complaining that I did not give it enough arguments.

Of course, ultimately, I need to figure out how to create a controller to allow me to insert new entries into the table... but I'll take my learning a step at a time and be grateful just to successfully pre-populate the table with multiple rows via the websetup.py file. Hopefully that will give me the clues to allow me to take it to the next step.

Thanks in advance!

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

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

发布评论

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

评论(1

会发光的星星闪亮亮i 2024-08-10 19:39:14

嗯,你的问题很简单(令我印象深刻的是,它这么长时间都没有得到答复:)。

Well your problem is simply (I'm impressed it went unanswered for so long :).

  • First why name your id column "djID"? why not just id?
  • Second you don't insert into it, that is why it's autoincrement.
  • Third the first basic SA tutorial explains this
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文