This article explains how to assign the owner ID automatically when creating a new post to avoid SQL errors.
In a previous lesson, we encountered an error during post creation. Instead of creating a new post successfully, the application returned a 500 status code. The logs revealed an SQL error indicating that a null value in the “owner_id” column violates the NOT NULL constraint.
The error log was as follows:
Copy
Ask AI
line 1771, in _execute_context self.dialect.do_execute(File "C:\users\sanje\documents\courses\fastapi\venv\lib\site-packages\sqlalchemy\engine\default.py", line 717, in do_execute cursor.execute(statement, parameters)sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "owner_id" violates not-null constraint[SQL: INSERT INTO posts (title, content, published, owner_id) VALUES (%(title)s, %(content)s, %(published)s, %(owner_id)s) RETURNING posts.id][parameters: {'title': 'top beaches in florida', 'content': 'something something beaches', 'published': True, 'owner_id': None}](Background on this error at: https://sqlalche.me/e/14/gkpj)
Despite the model expecting an owner ID, the post creation endpoint did not provide one. The SQL error confirms that when trying to insert a new post, the owner_id field was null.The post schema was purposefully designed to exclude the owner ID from the request body since the authenticated user should be automatically assigned as the owner. Below is the post schema:
Copy
Ask AI
from pydantic import BaseModel, EmailStrfrom datetime import datetimefrom typing import Optionalclass PostBase(BaseModel): title: str content: str published: bool = Trueclass PostCreate(PostBase): passclass Post(PostBase): id: int created_at: datetime owner_id: int class Config: orm_mode = True
To resolve the issue, update the POST endpoint to automatically assign the owner ID from the authenticated user:
Copy
Ask AI
@router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.Post)def create_posts(post: schemas.PostCreate, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)): # Using SQLAlchemy ORM to create a new post print(current_user.id) print(current_user.email) new_post = models.Post(owner_id=current_user.id, **post.dict()) db.add(new_post) db.commit() db.refresh(new_post) return new_post
With this change, every new post is automatically linked to the user who is currently authenticated. Testing this change should confirm that the owner ID is stored correctly. For example, executing the following SQL query:
Copy
Ask AI
SELECT * FROM users;
might show that the user with ID 23 (e.g., Sanjeev at Gmail.com) is correctly associated with the new post.
The critical change is updating the post creation logic to include:new_post = models.Post(owner_id=current_user.id, **post.dict())This adjustment ensures that each post is automatically linked to its creator.