7

Using postgres in python,

  1. How do I replace all fields from the same column that match a specified value? For example, let's say I want to replace any fields that match "green" with "red" in the "Color" column.

  2. How to delete all fields from the same column that match a specified value? For example, I'm trying to deleted all fields that match "green" in the Color column.

1 Answer 1

9

Ad1. You need something like this:

session.query(Foo).filter_by(color = 'green').update({ 'color': 'red' })
session.commit()

Ad2. Similarly:

session.query(Foo).filter_by(color = 'green').delete()
session.commit()

You can find the querying documentation here and here.

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

3 Comments

I think the second answer deletes the entire row. I actually only want to delete the field.
I tried to use something like this to make field empty but it not seem to work: session.query(Foo).filter_by(color = 'green').update({ 'color': '' })
session.query(Foo).filter_by(color = 'green').update({ 'color': '' }) should work just fine. Maybe you didn't commit? Anyway, creating the engine with echo = True (or configuring sqlalchemy.engine logger) should help you debug that.

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.