CodexBloom - Programming Q&A Platform

FastAPI with SQLAlchemy - IntegrityError when Trying to Insert Related Data

👀 Views: 42 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
fastapi sqlalchemy postgresql Python

I've hit a wall trying to I'm working with an scenario while trying to insert related data into my database using FastAPI with SQLAlchemy. I'm using PostgreSQL and getting an `IntegrityError` when attempting to save a new `Post` that has a foreign key reference to a `User`. The behavior message states `duplicate key value violates unique constraint`. It seems like the user is not being correctly referenced. Here's the relevant code snippet: ```python from fastapi import FastAPI, HTTPException from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String, unique=True) class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String) content = Column(String) user_id = Column(Integer, ForeignKey('users.id')) user = relationship('User') DATABASE_URL = "postgresql://user:password@localhost/db" engine = create_engine(DATABASE_URL) Base.metadata.create_all(bind=engine) app = FastAPI() @app.post('/posts/') async def create_post(title: str, content: str, username: str): with sessionmaker(bind=engine)() as session: user = session.query(User).filter(User.username == username).first() if not user: raise HTTPException(status_code=404, detail='User not found') new_post = Post(title=title, content=content, user_id=user.id) session.add(new_post) session.commit() return new_post ``` When I try to create a post with a user that already exists in the database, I get this behavior, even though I have confirmed that the `User` is already present. I've verified that the username exists before creating the post, and I'm correctly referencing the `user_id`. I've also checked the database for duplicates but there are none for the usernames. Any insights on what might be causing this scenario? Is there something wrong with how I'm handling the relationships in SQLAlchemy? This is part of a larger REST API I'm building. Any examples would be super helpful.