Working removal of custom fields

This commit is contained in:
shamoon
2023-10-31 13:09:05 -07:00
parent 44728aa048
commit 7879b9e91b
12 changed files with 122 additions and 38 deletions

View File

@@ -219,6 +219,13 @@ class Migration(migrations.Migration):
),
],
),
migrations.AddConstraint(
model_name="customfield",
constraint=models.UniqueConstraint(
fields=("name",),
name="documents_customfield_unique_name",
),
),
migrations.AddConstraint(
model_name="customfieldinstance",
constraint=models.UniqueConstraint(

View File

@@ -916,6 +916,12 @@ class CustomField(models.Model):
ordering = ("created",)
verbose_name = _("custom field")
verbose_name_plural = _("custom fields")
constraints = [
models.UniqueConstraint(
fields=["name"],
name="%(app_label)s_%(class)s_unique_name",
),
]
def __str__(self) -> str:
return f"{self.name} : {self.data_type}"

View File

@@ -464,7 +464,7 @@ class DocumentSerializer(OwnedObjectSerializer, DynamicFieldsModelSerializer):
field_instance["value"] = data_custom_field["value"]
return values
def update(self, instance, validated_data):
def update(self, instance: Document, validated_data):
if "custom_fields" in validated_data:
custom_fields = validated_data.pop("custom_fields")
for field_data in custom_fields:
@@ -473,6 +473,19 @@ class DocumentSerializer(OwnedObjectSerializer, DynamicFieldsModelSerializer):
field=field_data["field"],
value=field_data["value"],
)
existing_fields = CustomFieldInstance.objects.filter(document=instance)
for existing_field in existing_fields:
if (
not len(
[
f
for f in custom_fields
if f["field"]["id"] == existing_field.field.id
],
)
> 0
):
existing_field.delete()
if "created_date" in validated_data and "created" not in validated_data:
new_datetime = datetime.datetime.combine(
validated_data.get("created_date"),