尝试使用 FastAPI/ SQLite 进行 POST 时获取 (sqlite3.IntegrityError) NOT NULL 约束失败
出现以下错误
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: SignalJourneyAudienceConstraints.constraintId
[SQL: INSERT INTO "SignalJourneyAudienceConstraints" ("sourceId", "constraintTypeId", "constraintValue", targeting, frequency, period) VALUES (?, ?, ?, ?, ?, ?)]
[parameters: (None, 10, 'STRING', 1, None, None)]
尝试使用以下端点时 。我已经将所有字段设置为除了:
- constraintTypeId: int
- constrainValue: strtargeting
- : bool
暂时作为可选字段。
端点
# mail.py
...
@app.post("/add-new-audience-constraint", status_code=status.HTTP_200_OK)
def add_new_audience_constraint(
sjac: schema.SignalJourneyAudienceConstraints, db: Session = Depends(get_db)
):
"""Sets the main query data."""
new_audience_constraint = models.SignalJourneyAudienceConstraints(
constraintTypeId=sjac.constraintTypeId,
constraintValue=sjac.constraintValue.upper(),
targeting=True,
)
db.add(new_audience_constraint)
db.commit()
return {"message": "Data added successfully."}
模型
# models.py
class SignalJourneyAudienceConstraints(Base):
"""Signal Journey Audience Constraints"""
__tablename__ = "SignalJourneyAudienceConstraints"
constraintId = Column(Integer, primary_key=True)
audienceId = Column(
Integer,
ForeignKey("SignalJourneyAudiences.audienceId"),
primary_key=True,
)
sourceId = Column(Integer, ForeignKey("SignalJourneySources.sourceId"))
constraintTypeId = Column(
Integer, ForeignKey("SignalJourneyConstraintType.constraintTypeId")
)
constraintValue = Column(String)
targeting = Column(Boolean)
frequency = Column(Integer)
period = Column(Integer)
架构
# schema.py
class SignalJourneyAudienceConstraints(BaseModel):
"""SignalJourneyAudienceConstraints BaseModel."""
constraintId: Optional[int] # PK
audienceId: Optional[int] # FK - SignalJourneyAudiences -> audienceId
sourceId: Optional[int] # FK - SignalJourneySources -> sourceId
constraintTypeId: int # FK - SignalJourneyConstraintType -> constraintTypeId
constraintValue: str
targeting: bool
frequency: Optional[int]
period: Optional[int]
class Config:
"""config class"""
orm_mode = True
我已经研究了其他SO问题,但似乎没有一个适合我所经历的。希望有人可以解释发生了什么以及如何解决它
ERD
I am getting the following error
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: SignalJourneyAudienceConstraints.constraintId
[SQL: INSERT INTO "SignalJourneyAudienceConstraints" ("sourceId", "constraintTypeId", "constraintValue", targeting, frequency, period) VALUES (?, ?, ?, ?, ?, ?)]
[parameters: (None, 10, 'STRING', 1, None, None)]
When trying to use the below endpoint. I have made all fields except:
- constraintTypeId: int
- constraintValue: str
- targeting: bool
As optional for the time being.
Endpoint
# mail.py
...
@app.post("/add-new-audience-constraint", status_code=status.HTTP_200_OK)
def add_new_audience_constraint(
sjac: schema.SignalJourneyAudienceConstraints, db: Session = Depends(get_db)
):
"""Sets the main query data."""
new_audience_constraint = models.SignalJourneyAudienceConstraints(
constraintTypeId=sjac.constraintTypeId,
constraintValue=sjac.constraintValue.upper(),
targeting=True,
)
db.add(new_audience_constraint)
db.commit()
return {"message": "Data added successfully."}
Model
# models.py
class SignalJourneyAudienceConstraints(Base):
"""Signal Journey Audience Constraints"""
__tablename__ = "SignalJourneyAudienceConstraints"
constraintId = Column(Integer, primary_key=True)
audienceId = Column(
Integer,
ForeignKey("SignalJourneyAudiences.audienceId"),
primary_key=True,
)
sourceId = Column(Integer, ForeignKey("SignalJourneySources.sourceId"))
constraintTypeId = Column(
Integer, ForeignKey("SignalJourneyConstraintType.constraintTypeId")
)
constraintValue = Column(String)
targeting = Column(Boolean)
frequency = Column(Integer)
period = Column(Integer)
Schema
# schema.py
class SignalJourneyAudienceConstraints(BaseModel):
"""SignalJourneyAudienceConstraints BaseModel."""
constraintId: Optional[int] # PK
audienceId: Optional[int] # FK - SignalJourneyAudiences -> audienceId
sourceId: Optional[int] # FK - SignalJourneySources -> sourceId
constraintTypeId: int # FK - SignalJourneyConstraintType -> constraintTypeId
constraintValue: str
targeting: bool
frequency: Optional[int]
period: Optional[int]
class Config:
"""config class"""
orm_mode = True
I have looked into other SO questions, but none seem to fit what I am experiencing. Hopefully someone can explain what's going on and how to resolve it
ERD
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有两个字段列为primary_key;它们都是主键吗?由于您有两个字段,因此主键字段不会自动定义为自增字段;为此,您只想有一个主键,即整数字段。
SQLAlchemy 只会自动为 SQLite 设置
auto_increment
属性 当有一个主键列并且它被定义为整数时。由于定义复合键不是您想要的,因此使用
constraintId
作为单个自动递增键(如 ERD 中所示)就是您想要的 - 删除primary_key
条目对于audienceId
字段。You have two fields listed as primary_key; are they both primary keys? Since you have two fields, the primary key field will not automagically defined as an auto increment field; for that you want to only have one primary key, integer field.
SQLAlchemy will only set the
auto_increment
property for SQLite automagically when there is a single primary key column and it's defined as an integer.Since defining a composite key wasn't what you wanted, using
constraintId
as a single auto incrementing key (as shown in your ERD) is what you want - remove theprimary_key
entry foraudienceId
field.