<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _prepare_related_single_or_m2m_relations(self, validated_data):
 """ Handle writing to nested related model fields for both single and many-to-many relationships. For single relationships, any existing or new instance resulting from the provided data is set back into the provided `validated_data` to be applied by DjangoRestFramework's default handling. For M2M relationships, any existing or new instances resulting from the provided data are returned in a dictionary mapping M2M field names to a list of instances to be related. The actual relationship is then applied by `_write_related_m2m_relations` because DjangoRestFramework does not support assigning M2M fields. """

        many_to_many_relationships = {}
        for fieldname, field in self.get_fields().items():
            if (
                # `ModelSubSerializer` is handled separately
                isinstance(field, ModelSubSerializer) or
                # Skip read-only fields, obviously
                field.read_only or
                # Only list or model serializers are supported
                not (
                    isinstance(field, serializers.ModelSerializer) or
                    isinstance(field, serializers.ListSerializer)
                )
            ):
                continue  # Skip field

            is_list_field = isinstance(field, serializers.ListSerializer)

            if is_list_field:
                ModelClass = field.child.Meta.model
                field_data_list = validated_data.pop(fieldname, [])
            else:
                ModelClass = field.Meta.model
                field_data_list = validated_data.pop(fieldname, None)
                field_data_list = field_data_list and [field_data_list] or []

            # Skip field if no data was provided
            if not field_data_list:
                continue

            related_instances = []
            for field_data in field_data_list:
                related_instance = \
                    self._get_or_update_or_create_related_instance(
                        ModelClass, fieldname, field_data)
                if related_instance:
                    related_instances.append(related_instance)

            # Add related model instance as validated data parameter for
            # later create/update operation on parent instance.
            if not is_list_field:
                validated_data[fieldname] = related_instances[0]
            # Many-to-many relationships must be handled after super's `create`
            # or `update` method, not here. So we just return the list for now
            else:
                many_to_many_relationships[fieldname] = related_instances
        return many_to_many_relationships