尝试在sqlite数据库中插入数据时,标题中出现此错误。数据来自前端的表单。
我定义了两个实体模型,一个人和一个车辆。它们在类型一(人)与许多(车辆)相关。 我在文件controllers.py上使用此模型在其上插入数据。
### file models.py
from app import db
class Person(db.Model):
__tablename__ = 'person'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False)
first_name = db.Column(db.String(100), nullable=False)
last_name = db.Column(db.String(100), nullable=False)
cpf = db.Column(db.String(16), nullable=False, unique=True)
email = db.Column(db.String(300), nullable=False, unique=True)
owns = db.relationship('Vehicle')
def __init__(self, username, password, first_name, last_name, cpf, email):
self.username = username
self.password = password
self.first_name = first_name
self.last_name = last_name
self.cpf = cpf
self.email = email
@property
def is_authenticated(self):
return True
@property
def is_active(sef):
return True
@property
def is_anonymous(sef):
return False
def get_id(self):
return str(self.id)
def __repr__(self):
return "<UsersLogin %r>" % self.username
class Vehicle(db.Model):
__tablename__ = 'vehicle'
id = db.Column(db.Integer, primary_key=True)
person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
license_plate = db.Column(db.String(20))
crlv = db.Column(db.String(600))
crv = db.Column(db.String(600))
def __init__(self, license_plate, crlv, crv):
self.license_plate = license_plate
self.crlv = crlv
self.crv = crv
### file controllers.py
### codes...
if current_user.is_authenticated:
person = Person.query.filter_by(id=current_user.id).first()
new_vehicle = Vehicle(
license_plate=form.license_plate.data,
crlv=form.crlv.data,
crv=form.crv.data,
)
person.owns.append(new_vehicle)
db.session.add(new_vehicle)
db.session.commit()
flash("Congrats! Your vihicle was recorded on our system!")
return redirect(url_for("index"))
我想向人员添加新的Vehicle,该人员已经存在于我的数据库中。那就是问题所在。当我尝试这样做时,出现以下错误:
sqlalchemy.exc.IntegrityError:(sqlite3.IntegrityError)检查约束失败:车辆 [SQL:INSERT INTO车辆(person_id,license_plate,crlv,crv)值(?,?,?,?) [参数:(2,'4','3','4')]
数据来自前端。
请,任何人都可以帮助我停止我的代码中的此错误?