我正在尝试使用SQLAlchemy在表中定义主键。问题是由于以下错误,我无法执行此操作:
ArgumentError: Mapper Mapper|BankAccount|bank_account could not assemble any primary key columns for mapped table 'bank_account'
我的代码就是这个:
from flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' +
os.path.join(basedir,'db.sqlite')
app.config ['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# init db
db = SQLAlchemy(app)
# init marshmallow
ma = Marshmallow(app)
# class account
class BankAccount(db.Model):
number_acc: db.Column(db.String(50), primary_key = True)
owner_acc: db.Column(db.String(50))
bank: db.Column(db.String(50))
amount_acc: db.Column(db.Float)
# constructor of the class
def __init__(self,number_acc,owner_acc,bank,amount_acc):
self.number_acc = number_acc
self.owner_acc = owner_acc
self.bank = bank
self.amount_acc = amount_acc
如何在表bank_account
中插入主键?
答案 0 :(得分:1)
SQLAlchemy Column
对象的类型不是annotations,因此必须将它们分配为类属性-请参见"Declaring a Mapping"和"Mapping Table Columns":
class BankAccount(db.Model):
number_acc = db.Column(db.String(50), primary_key = True)
owner_acc = db.Column(db.String(50))
bank = db.Column(db.String(50))
amount_acc = db.Column(db.Float)
在当前尝试中,实际上Declarative没有在类构造期间找不到的列,因为列信息隐藏在注释中。