<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def update_query(self, query_id, name=None, filter=None, **kwargs):
 """Update existing query in device query service. .. code-block:: python q.filter["custom_attributes"]["foo"] = { "$eq": "bar" } new_q = api.update_query( query_id = q.id, name = "new name", filter = q.filter ) :param str query_id: Existing query ID to update (Required) :param str name: name of query :param dict filter: query properties to apply :return: the newly updated query object. :rtype: Query """

        # Get urlencoded query attribute
        filter_obj = filters.legacy_filter_formatter(
            dict(filter=filter),
            Device._get_attributes_map()
        ) if filter else None

        query_map = Query._create_request_map(kwargs)

        # The filter option is optional on update but DeviceQueryPostPutRequest sets it None, which is invalid.
        # Manually create a resource body without the filter parameter if only the name is provided.
        if filter is None:
            body = {"name": name}
        else:
            body = DeviceQueryPostPutRequest(name=name, query=filter_obj['filter'], **query_map)

        api = self._get_api(device_directory.DefaultApi)
        return Query(api.device_query_update(query_id, body))