简体   繁体   中英

sqlalchemy: Updating a database using python

I have this Post Model

class Post(Base):
__tablename__ = "posts"

id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default='True')
owner = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, 
                                  server_default=text('now()'))

I tried to modify an existing row with this python code but I'm getting the error:

File ".\app\main.py", line 118, in update_post post.update() AttributeError: 'Post' object has no attribute 'update'

@app.put("/posts/{id}", status_code=status.HTTP_202_ACCEPTED)
def update_post(id: int, db: Session = Depends(get_db)):  

post = db.query(models.Post).filter(models.Post.id == id).first()
   
if post == None:
    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No post with 
              that Id, {id}")

post.update()   
db.commit()     
            

return {"data": post}

I am using python 3.10 What am I doing wrong?

It's not the way we update records in sqlalchemy. If you already have an object just replace fields you want to update

post.title = "new title"
post.owner = "new owner"
...
db.commit()

Interesting fact, to fetch single unique record you could just write

post = db.query(models.Post).get(id)

Apparently, the post I was pointing to referenced the schema which of course doesn't have the update attribute, I have to differentiate the post I want to update.

This now works for me.

@app.put("/posts/{id}", status_code=status.HTTP_202_ACCEPTED)
def update_post(id: int, ***updated_post: Post***, db: Session = Depends(get_db)):  

post = db.query(models.Post).filter(models.Post.id == id).first()

if post == None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No post with 
          that Id, {id}")

post.update(updated_post.dict(), synchronize_session=False)   
db.commit()     
        

return {"data": ***updated_post***}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM