为什么UniqueConstraint不能在flask_sqlalchemy中工作

时间:2017-05-15 09:04:31

标签: python sqlalchemy

我想要另外一个Django的<section> <div class="container"> <input id="textfield" type="text" name="tag" placeholder="Enter an item and press Enter to add to list"> <div class="tags"></div> </div> </section>,似乎unique_together是我正在寻找的,但不适合我。

这是一个例子:

UniqueConstraint

测试它:

import os
from flask import Flask
from flask_script import Manager, Shell
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

manager = Manager(app)
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'users'
    __table_args__ = tuple(db.UniqueConstraint('name', 'address'))
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    address = db.Column(db.String(64), nullable=False)

    def __repr__(self):
        return '<User (%s, %s)>' % (self.name, self.address)


def make_shell_context():
    return dict(app=app, db=db, user=User)
manager.add_command("shell", Shell(make_context=make_shell_context))


if __name__ == '__main__':
    manager.run()

我也尝试过:

$ python test.py shell

In [1]: db.create_all()

In [2]: u1=user(name='a', address='x'); u2=user(name='a', address='x'); 
db.session.add(u1); db.session.add(u2); db.session.commit()

In [3]: user.query.all()
Out[3]: [<User (a, x)>, <User (a, x)>]

也不起作用,它有什么问题?

2 个答案:

答案 0 :(得分:7)

UniqueConstraint的实例是可迭代的,在这种情况下似乎立即停止迭代,所以

tuple(db.UniqueConstraint('name', 'address'))
当你想要一个包含1个项目的元组时,

会产生一个空元组,即约束实例。使用

__table_args__ = (db.UniqueConstraint('name', 'address'), )

或任何其他变体。至于为什么后一种形式不起作用,你在声明中must apply table-level constraint objects using __table_args__

答案 1 :(得分:0)

传递变量名(而不是字符串)对我有用。

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    address = db.Column(db.String(64), nullable=False)
    db.UniqueConstraint(name, address)