17558 raise validation error if removing choice from choiceset that is currently used

This commit is contained in:
Arthur Hanson 2024-09-24 10:23:16 -07:00
parent 983032189a
commit b59ae0fd93

View File

@ -823,27 +823,31 @@ class CustomFieldChoiceSet(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel
raise ValidationError(_("Must define base or extra choices.")) raise ValidationError(_("Must define base or extra choices."))
# check if removing any used choices # check if removing any used choices
original_choices = [obj[1] for obj in self._original_extra_choices] if self._original_extra_choices:
new_choices = [obj[1] for obj in self.extra_choices] original_choices = new_choices = []
diff_choices = list(set(original_choices) - set(new_choices)) original_choices = [obj[1] for obj in self._original_extra_choices]
if diff_choices: if self.extra_choices:
# CustomFields using this ChoiceSet new_choices = [obj[1] for obj in self.extra_choices]
for custom_field in self.choices_for.all():
for object_type in custom_field.object_types.all(): diff_choices = list(set(original_choices) - set(new_choices))
# unfortunately querying the whole array of diff_choices doesn't work if diff_choices:
for choice in diff_choices: # CustomFields using this ChoiceSet
# Need to OR query as can be multiple choice or single choice so for custom_field in self.choices_for.all():
# have to do both contains and equals to catch both for object_type in custom_field.object_types.all():
query_args = { # unfortunately querying the whole array of diff_choices doesn't work
f"custom_field_data__{custom_field.name}__contains": choice, for choice in diff_choices:
f"custom_field_data__{custom_field.name}": choice # Need to OR query as can be multiple choice or single choice so
} # have to do both contains and equals to catch both
if object_type.model_class().objects.filter(models.Q(**query_args, _connector=models.Q.OR)).exists(): query_args = {
raise ValidationError( f"custom_field_data__{custom_field.name}__contains": choice,
_("Cannot remove choice {choice} as it is used in model {model}").format( f"custom_field_data__{custom_field.name}": choice
choice=choice, model=object_type }
if object_type.model_class().objects.filter(models.Q(**query_args, _connector=models.Q.OR)).exists():
raise ValidationError(
_("Cannot remove choice {choice} as it is used in model {model}").format(
choice=choice, model=object_type
)
) )
)
def save(self, *args, **kwargs): def save(self, *args, **kwargs):