dsnewguy
dsnewguy

Reputation: 63

How to fix, PostgreSQL BEFORE UPDATE Trigger on selected columns executed from Django side on the columns not associated with the Trigger?

Basically, I am creating a Django app with a PostgreSQL database, now for a given table on a database I have to use Triggers for preventing update on selected columns, Trigger is working properly from the database side doing what it is made to do, preventing update on selected columns and allowing to update non-associated column with trigger.

Now from the Django side, whenever I try to update the table's fields/columns which are not associated with the trigger, it invokes/executes the trigger preventing the update operation for those not associated fields/columns and this trigger is even being executed when trying to add new record or data from Django side preventing insertion of new record.

Can anyone please help?

Thank you

Upvotes: 1

Views: 207

Answers (1)

dsnewguy
dsnewguy

Reputation: 63

I found the solution to my problem.

I created a PostgreSQL trigger to prevent the updating of a few columns. From the database side, I tested it and is working completely fine. The problem was with the Django side.

In the database, a single column can be updated by entering a value, it has no connection with other columns so no error in updating the specific column. For example, a row has two fields, one modifiable and other is prevented with a trigger, so when I modify that modifiable field it will be modified.

The problem with Django, in Django, it will always write the whole object. Like, if you have an object with two fields, one modifiable, the other not, but both are mapped in Django, when you save that object, Django will update both fields, even if only one or none of them have changed.

As the Django update all the fields even if only one field was being changed, the trigger was being invoked.

so I had to look for an option that will allow only to update specified fields or changed/modified fields only and not the other unchanged fields.

I found this update_fields,

update_fields helps me specific which fields should be updated instead of updating the whole row or all the fields.

Upvotes: 1

Related Questions