尝试使用 FastAPI/ SQLite 进行 POST 时获取 (sqlite3.IntegrityError) NOT NULL 约束失败

发布于 2025-01-09 19:09:07 字数 2739 浏览 1 评论 0原文

出现以下错误

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

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2025-01-16 19:09:07

您有两个字段列为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 the primary_key entry for audienceId field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文