Efficient way of passing params in SQLAlchemy

  • Instead of passing each parameter individually like this:

@app.post("/posts", status_code=status.HTTP_201_CREATED)
def create_posts(post: Post, db: Session = Depends(get_db)):

    # Like this:
    new_post = models.Post(title=post.title, content=post.content, published=post.published)

    db.add(new_post)
    db.commit()
    db.refresh(new_post)

    return { "data": new_post }
  • We can convert it to a dictionary and unpack it in the same format as this is a pydantic model

@app.post("/posts", status_code=status.HTTP_201_CREATED)
def create_posts(post: Post, db: Session = Depends(get_db)):

    # Like this:
    new_post = models.Post(**post.dict())

    db.add(new_post)
    db.commit()
    db.refresh(new_post)

    return { "data": new_post }

Last updated