0

I have a table in MySql DB. I need to update a particular column for all the rows in the table. I need to do this in a single call without deleting the rows, only updating the column values.

I have tried using df.to_sql(if_exists='replace') but this deletes the rows and re-inserts them. Doing so drops the rows from other table which are linked by the foreign key.

merge_df = merge_df[['id', 'deal_name', 'fund', 'deal_value']]
for index, row in merge_df.iterrows():
        ma_deal_obj = MA_Deals.objects.get(id=row['id'])
        ma_deal_obj.deal_value = row['deal_value']
        ma_deal_obj.save()

merge_df has other columns as well. I only need to update the 'deal_value' column for all rows.

One solution I have is by iterating over the dataframe rows and using Django ORM to save the value but this is quite slow for too many rows.

3
  • Does this answer your question? How to update multiple rows with single MySQL query in python? Commented Oct 31, 2019 at 17:46
  • 1
    So are you saying you need to execute UPDATE MA_Deals SET deal_value = 'new-value'; Commented Oct 31, 2019 at 17:51
  • @MarlinPierce No, that would make the value of deal_value = 'new-value' for all rows, I need to set different values of deal value for each row. Something like UPDATE MA_Deals SET deal_value = 'new-value1' where id = 1; UPDATE MA_Deals SET deal_value = 'new-value2' where id = 2; UPDATE MA_Deals SET deal_value = 'new-value3' where id = 3; All this but in a single call This is what I was looking for. Commented Jan 3, 2020 at 17:37

0

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.