def add_form_columns(self, form): """Given a group and a form, create the DB objects for each column in the form (if necessary) and add the form's columns to the group""" table_name = form.table_name column_names = form.get_data_column_names() column_types = form.get_data_column_types() for name, type in zip(column_names, column_types): # Get the pointer object for this form, or create it if # this is the first time we've used this form/column pointer = FormDataPointer.objects.get_or_create(form=form, column_name=name, data_type=type)[0] # Get or create the column group. If any other column had this # name and data type it will be used with this. try: column_group = self.columns.get(name=name, data_type=type) except FormDataColumn.DoesNotExist: # add a second check for the name, so we don't have duplicate # names inside a single form definition which will make queries # pretty challenging name = get_unique_value(self.columns, "name", name) column_group = FormDataColumn.objects.create(name=name, data_type=type) # don't forget to add the newly created column to this # group of forms as well. self.columns.add(column_group) self.save() column_group.fields.add(pointer) column_group.save()
def from_forms(cls, forms, domain): """Create a group from a set of forms. Walks through all of the forms' root tables and creates columns for each column in the form's table. If the column name and data type match a previously seen data column then the column is remapped to that column, otherwise a new column is created. Like many elements of CommCare HQ, the views and queries that are used by these models will pretty much exclusively work in mysql. """ if not forms: raise Exception("You can't create a group of empty forms!") # the name will just be the xmlns of the first form. We assume # that the majority of times (if not all times) this method will # be called is to harmonize a set of data across verisons of # forms with the same xmlns. name = forms[0].target_namespace now = datetime.utcnow() view_name = get_unique_value( FormDataGroup.objects, "view_name", format_table_name(name, prefix="view_", domain_name=domain.name) ) group = cls.objects.create(name=name, display_name=name, created=now, view_name=view_name, domain=domain) group.forms = forms group.save() for form in forms: group.add_form_columns(form) group.update_view() return group