How to ignoring columns on model save

405 views
Skip to first unread message

ro...@tonic-solutions.com

unread,
Jun 27, 2022, 5:36:50 AM6/27/22
to Django users
I have a model that is backed by a database table that contains a read-only column that is maintained by the database using Postgresql's Generated Columns (i.e. using GENERATED ALWAYS AS) - see https://www.postgresql.org/docs/current/ddl-generated-columns.html.

When Django saves the model, it tries to set the field, which throws `django.db.utils.ProgrammingError: cannot insert into column "_search". DETAIL: Column "_search" is a generated column.

Is there any way to tell Django not to attempt to insert that field?

From what I can tell `editable=False` doesn't prevent Django from trying to save it - which makes sense for fields that aren't editable by users but are calculated by the model class, e.g. in `save()`.

I know I could set `something like `instance.save(update_fields=[field for field in instance._meta.fields if field.name != "_search")` but it would need to be set on every save for that model throughout the application, which seems like a lot of technical debt and likely to trip up other developers as they maintain the application.

Is there anything that I can set on the field instance in the model to tell Django that it is maintained by the database?

If not, please can anyone suggest a way to add code to the model to make it ignore the field when saving?

Thanks

Roger

Jason

unread,
Jun 28, 2022, 7:33:24 AM6/28/22
to Django users
https://code.djangoproject.com/ticket/21454

there's an open ticket about this, some things might help you there.  But right now, there's no easy way to get around this

Ryan Nowakowski

unread,
Jun 28, 2022, 5:16:04 PM6/28/22
to django...@googlegroups.com


On June 27, 2022 4:36:49 AM CDT, "ro...@tonic-solutions.com" <ro...@tonic-solutions.com> wrote:
>I know I could set `something like `instance.save(update_fields=[field for
>field in instance._meta.fields if field.name != "_search")` but it would
>need to be set on every save for that model throughout the application,
>which seems like a lot of technical debt and likely to trip up other
>developers as they maintain the application.

You could override the save method on your model to always exclude _search from update_fields. That way you DRY.
Reply all
Reply to author
Forward
0 new messages