Automatically prune removed options from existing instances

This commit is contained in:
shamoon
2024-11-16 09:39:20 -08:00
parent 233212d198
commit e08fd79265
3 changed files with 93 additions and 17 deletions

View File

@@ -367,21 +367,6 @@ class CannotMoveFilesException(Exception):
pass
# should be disabled in /src/documents/management/commands/document_importer.py handle
@receiver(models.signals.post_save, sender=CustomField)
def update_cf_instance_documents(sender, instance: CustomField, **kwargs):
"""
'Select' custom field instances get their end-user value (e.g. in file names) from the select_options in extra_data,
which is contained in the custom field itself. So when the field is changed, we (may) need to update the file names
of all documents that have this custom field.
"""
if (
instance.data_type == CustomField.FieldDataType.SELECT
): # Only select fields, for now
for cf_instance in instance.fields.all():
update_filename_and_move_files(sender, cf_instance)
# should be disabled in /src/documents/management/commands/document_importer.py handle
@receiver(models.signals.post_save, sender=CustomFieldInstance)
@receiver(models.signals.m2m_changed, sender=Document.tags.through)
@@ -520,6 +505,34 @@ def update_filename_and_move_files(
)
# should be disabled in /src/documents/management/commands/document_importer.py handle
@receiver(models.signals.post_save, sender=CustomField)
def check_paths_and_prune_custom_fields(sender, instance: CustomField, **kwargs):
"""
When a custom field is updated:
1. 'Select' custom field instances get their end-user value (e.g. in file names) from the select_options in extra_data,
which is contained in the custom field itself. So when the field is changed, we (may) need to update the file names
of all documents that have this custom field.
2. If a 'Select' field option was removed, we need to nullify the custom field instances that have the option.
"""
if (
instance.data_type == CustomField.FieldDataType.SELECT
): # Only select fields, for now
for cf_instance in instance.fields.all():
options = instance.extra_data.get("select_options", [])
try:
next(
option["label"]
for option in options
if option["id"] == cf_instance.value
)
except StopIteration:
# The value of this custom field instance is not in the select options anymore
cf_instance.value_select = None
cf_instance.save()
update_filename_and_move_files(sender, cf_instance)
def set_log_entry(sender, document: Document, logging_group=None, **kwargs):
ct = ContentType.objects.get(model="document")
user = User.objects.get(username="consumer")