def get_or_create_userprofile()

in pulseapi/creators/serializers.py [0:0]


def get_or_create_userprofile(data, id_key):
    """
    Deserialize data into a `UserProfile` object.
    The `data` is checked for a value corresponding to the id_key.
    If it exists, we get the corresponding `UserProfile` object, otherwise
    we create a new `UserProfile` object with the name specified.
    We don't save the instance to the database and that is left to
    the calling function to save the instance.

    Returns a dictionary with two keys - `object` and `created`,
    where `object` is the retrieved or created `UserProfile` instance and
    `created` is a boolean specifying whether a new instance was created
    """
    profile_id = data.get(id_key)
    name = data.get('name')

    if not profile_id and not name:
        raise ValidationError(
            detail=_('A creator/profile id or a name must be provided.'),
            code='missing data',
        )

    if profile_id:
        try:
            return UserProfile.objects.get(id=profile_id), False
        except ObjectDoesNotExist:
            raise ValidationError(
                detail=_('No profile exists for the given id {id}.'.format(id=profile_id)),
                code='invalid',
            )

    return UserProfile(custom_name=name), True