本文介绍了为什么 UniqueConstraint 在flask_sqlalchemy 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在烧瓶中使用 Django unique_together 的替代品,似乎 UniqueConstraint 是我正在寻找的,但对我不起作用.

I want an alternative of Django's unique_together in flask, seems UniqueConstraint is what I'm looking for, but doesn't work for me.

示例如下:

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)>]

我也试过:

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')

也不行,有什么问题吗?

not work either, what's wrong with it?

推荐答案

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

An instance of UniqueConstraint is iterable and in this case seems to stop iteration immediately, so

tuple(db.UniqueConstraint('name', 'address'))

导致一个空元组,当你想要一个包含 1 个项目的元组时,约束实例.使用

results in an empty tuple, when you wanted a tuple that contains 1 item, the constraint instance. Use

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

或任何其他变体.至于为什么后一种形式不起作用,你必须在声明中使用 __table_args__ 应用表级约束对象.

or any other variation instead. As to why the latter form does not work, you must apply table-level constraint objects using __table_args__ in declarative.

这篇关于为什么 UniqueConstraint 在flask_sqlalchemy 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 13:44