为什么Flask SQL炼金术允许保存主键None?

问题描述 投票:1回答:1

尽管主键为空,并且主键字段中添加了nullable=False,Flask SQL Alchemy仍保存到DB(即使没有必要添加它)。>>

我正在分配ID,并且未使用正常的自动增量或SQL Alchemy附带的任何内容。

model.py

class User(db.Model):
  id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False)

  # passing in the ID manually
  @classmethod
  def new(cls, sender_id):
      try:
         db.create_all()
         d = cls()
         d.id = sender_id
         return d
      except Exception as e:
         print('Error in User new:', e)

   def insert(self):
      try:
          db.session.add(self)
          db.session.commit()
          print('INSERT OKAY')
      except Exception as e:
          print('RollBack', e)
          db.session.rollback()

test.py

#FLASK_ENV = 'dev_testing'
#----SETUP
# load env variables
def setup_testing_environment():
    load_dotenv(find_dotenv(".env", raise_error_if_not_found=True)

#test setup testing DB
def create_test_app():
    try:
        app = Flask(__name__)
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        if os.environ['FLASK_ENV'] == 'development' or os.environ['FLASK_ENV'] == 'dev_testing':
            setup_testing_environment()
        app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:"
        return app
    except Exception as e:
        print('Error in create_test_app', e)


#---- ACTUAL TEST
def test_should_fail(unittest.testcase):
    #assign DB and create context for test to run
    app = create_test_app()
    with app.app_context():
       db.init_app(app)
       # make ID value None;
       user = User.new(None)
       # <User id=None>
       user.insert()
      # fails - user *is* being added to DB 
       assert user in not db.session

       #end test
       db.session.remove()
       db.drop_all()

没有回滚发生。 SQL Alchemy没有显示任何错误。用户正在保存到数据库,但是由于没有ID,因此无法查找。用户表完全为空。

为什么SQL Alchemy无法捕捉到这一点?如何分配ID,以便它可以正常工作?

Flask SQL Alchemy尽管主键为空,但在主键字段中添加了nullable = False(即使没有必要添加),也会保存到DB。我分配的是ID,而不是...

python sqlalchemy flask-sqlalchemy
1个回答
0
投票

SQLAlchemy的作者指出了here

© www.soinside.com 2019 - 2024. All rights reserved.