1

Here is my code for updating postgresql DB table via sqlalchemy orm:

db_car_record = session.query(CarsTable).update({CarsTable.CarId : 37805,
                                                   CarsTable.AuctionId : 879})

session.commit()

I receive the duplicate key error. Do you have any idea?

sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) duplicate key value violates unique constraint "ix_carstable_CarId"
DETAIL:  Key ("CarId")=(37805) already exists.
 [SQL: 'UPDATE carstable SET "AuctionId"=%(AuctionId)s, "CarId"=%(CarId)s,
updated_on=%(updated_on)s'] [parameters: {'updated_on': datetime.datetime(2017, 8, 12, 3, 49, 23, 115733), 'CarId': 37805, 'AuctionId': 879}]
2
  • 3
    You already have a row in the db with CarId 37805. I'm not sure how to make that any clearer. Commented Aug 12, 2017 at 1:08
  • You'll want to move the id to a filter. Commented Aug 12, 2017 at 4:14

1 Answer 1

1

You want to change the AuctionId of the car that has a CarId of 37805?

car_to_change = session.query(CarsTable).filter(CarsTable.CarId==37805).first()
car_to_change.AuctionId = 879
session.commit()

You can also do:

# Notice difference between `filter` and `filter_by`
car_to_change = session.query(CarsTable).filter_by(CarId=37805).first()
car_to_change.AuctionId = 879
session.commit()

Here's a tutorial that'll get you started: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.