-
Notifications
You must be signed in to change notification settings - Fork 97
Description
Description
We have a couple of customized allocation request forms where we wanted to save the information provided to them from users. In order to avoid needing to add more columns to the allocation table to save this new information we have created a way to automatically create allocation attributes from the values provided in the forms. This prevents database migrations for each new form field and an admin needing to go in and create the allocation attributes themselves.
How it works:
- A new column is created in in the allocation attribute type table
linked_resource_attribute_type = models.ForeignKey(ResourceAttributeType, on_delete=models.CASCADE, blank=True, null=True)
- You assign a resource attribute type to this allocation attribute type
- When an allocation is requested a new allocation attribute is created if a resource attribute with a matching resource attribute type has a value from the form.
If this is of interest, I can create a pr for it.
The line # linked_resources__id__exact=resource_obj.id,
is for a separate feature we have added, and I can create a separate issue for. The linked_resource
is not the one that currently exists in ColdFront. This one allows you to assign allocation attribute types to a specific resource, I didn't pick a very good name for it.
Component
Allocations
Additional information
def add_allocation_attributes(self, resource_obj, form_data, allocation_obj):
# This section of code first grabs all the allocation attribute types that are linked to
# the selected resource. Then it makes sure the only allocation attribute types included
# are ones that have a linked resource attribute type that exists in a resource attribute
# the selected resource has.
allocation_attribute_type_objs = AllocationAttributeType.objects.filter(
# linked_resources__id__exact=resource_obj.id,
linked_resource_attribute_type__isnull=False
)
linked_resource_attribute_type_objs = [
allocation_attribute_type_obj.linked_resource_attribute_type
for allocation_attribute_type_obj in allocation_attribute_type_objs
]
resource_attribute_type_objs = resource_obj.resourceattribute_set.filter(
resource=resource_obj,
resource_attribute_type__in=linked_resource_attribute_type_objs
)
resource_attribute_type_objs = [
resource_attribute_type_obj.resource_attribute_type
for resource_attribute_type_obj in resource_attribute_type_objs
]
for allocation_attribute_type_obj in allocation_attribute_type_objs:
if allocation_attribute_type_obj.linked_resource_attribute_type in resource_attribute_type_objs:
value = form_data.get(allocation_attribute_type_obj.linked_resource_attribute_type.name)
if value is not None and value != '':
if type(value) == list:
value = ','.join(value)
AllocationAttribute.objects.create(
allocation_attribute_type=allocation_attribute_type_obj,
allocation=allocation_obj,
value=value
)