【问题标题】:sqlite3 schema for flask poll app烧瓶投票应用程序的 sqlite3 模式
【发布时间】:2011-07-30 12:58:04
【问题描述】:

我是Flask 初学者,我想使用flask 和sqlite3 作为数据库引擎来构建一个投票应用程序。

我的问题是如何创建两个表,“问题”和“选择”,以便每个问题都有一些选择(可能不是固定数字。

我最初的做法相当幼稚:

drop table if exists entries;
create table question (
    ques_id integer primary key autoincrement,
    ques string not null,
    choice1 string not null,
    choice2 string not null,
    choice3 string not null,
    choice4 string not null,
    pub_date integer
); 

【问题讨论】:

    标签: sqlite database-schema flask


    【解决方案1】:

    下面是比较normalized的做法。这有利于存储所有问题共有的一组单独的选项。

    CREATE TABLE choices (
        choice_id integer primary key autoincrement,
        choice string not null
    );
    
    CREATE TABLE questions (
        ques_id integer primary key autoincrement,
        ques string not null,
        choice_id integer,
        FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
    );
    

    示例解释器会话:

    >>> import sqlite3
    >>> conn = sqlite3.connect(':memory:')
    >>> c = conn.cursor()
    >>> c.execute("""CREATE TABLE choices (
    ...     choice_id integer primary key autoincrement,
    ...     choice string not null
    ... );""")
    <sqlite3.Cursor object at 0x7f29f60b8ce8>
    >>> c.execute("""CREATE TABLE questions (
    ...     ques_id integer primary key autoincrement,
    ...     ques string not null,
    ...     choice_id integer,
    ...     pub_date integer,
    ...     FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
    ... );""")
    <sqlite3.Cursor object at 0x7f29f60b8ce8>
    >>> c.execute("INSERT INTO choices (choice) VALUES ('yes')")
    <sqlite3.Cursor object at 0x7f29f60b8ce8>
    >>> c.execute("""INSERT INTO questions (ques,choice_id) 
                     VALUES ('do you like sqlite?',1)""")
    <sqlite3.Cursor object at 0x7f29f60b8ce8>
    >>> c.execute("""SELECT ques, choice 
                       FROM questions q 
                            JOIN choices c ON c.choice_id = q.choice_id;""")
    >>> c.fetchall()
    [(u'do you like sqlite?', u'yes')]
    

    【讨论】:

    • @Adam- 只是为了澄清我的困惑......架构的最后一行发生了什么?
    • @infoquad:我不能比 SQLite 自己关于该主题的出色文档做得更好:sqlite.org/foreignkeys.html Cheers。
    猜你喜欢
    • 2011-07-31
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2012-06-16
    相关资源
    最近更新 更多