def create_or_update_feature_state_values_for_feature_segments(apps, schema_editor):  # type: ignore[no-untyped-def]
    """
    Create / Update the FeatureStateValue object for all FeatureSegments
    that currently exist.
    """

    FeatureSegment = apps.get_model("features", "FeatureSegment")
    FeatureState = apps.get_model("features", "FeatureState")
    FeatureStateValue = apps.get_model("features", "FeatureStateValue")

    feature_state_values_to_update = []
    feature_state_values_to_create = []

    for feature_segment in FeatureSegment.objects.prefetch_related(
        Prefetch(
            "feature_states",
            queryset=FeatureState.objects.select_related("feature_state_value"),
        )
    ).all():
        # cast the feature states into a list since they are prefetched
        feature_states = list(feature_segment.feature_states.all())
        num_feature_states = len(feature_states)
        if num_feature_states != 1:
            logger.error(
                "Expected 1 FeatureState but FeatureSegment %d had %d"
                % (feature_segment.id, num_feature_states)
            )
            continue

        # we should only ever have a single feature state associated with a
        # feature segment (we should have used a OneToOneField, I know...)
        feature_state = feature_states[0]
        value_key = {INTEGER: "integer_value", BOOLEAN: "boolean_value"}.get(
            feature_segment.value_type, "string_value"
        )

        if not hasattr(feature_state, "feature_state_value"):
            # if the feature state doesn't already have a feature state value
            # then we need to create one and append it to the list to create
            feature_state_value = FeatureStateValue(
                feature_state=feature_state,
                type=feature_segment.value_type,
            )
            setattr(feature_state_value, value_key, feature_segment.value)
            feature_state_values_to_create.append(feature_state_value)
        else:
            # otherwise, if it does have a feature state value already, then we
            # just need to append it to the list to update
            feature_state.feature_state_value.type = feature_segment.value_type
            setattr(feature_state.feature_state_value, value_key, feature_segment.value)
            feature_state_values_to_update.append(feature_state.feature_state_value)

    FeatureStateValue.objects.bulk_create(feature_state_values_to_create)
    FeatureStateValue.objects.bulk_update(
        feature_state_values_to_update,
        fields=["type", "string_value", "boolean_value", "integer_value"],
    )

    Create / Update the FeatureStateValue object for all FeatureSegments
    that currently exist.
    
api/features/migrations/0028_auto_20210223_2039.py